I'm having issues with dependency injection.
I've tried both #EJB and #Autowired, but nothing works.
This is what i have now:
HomeController
#Controller
#ComponentScan(basePackages = "org.vives.repositories")
public class HomeController extends HttpServlet {
private final BeerRepository beerRepository;
#Autowired
public HomeController(BeerRepository beerRepository) {
this.beerRepository = beerRepository;
}
#GetMapping("/")
public String index(Model model) {
List<Brewer> brewers = this.beerRepository.getAll();
model.addAttribute("brewers", brewers);
return "index";
}
}
When I hover over beerRepository parameter, I get that:
BeerRepository
#Stateless
#Repository
public class BeerRepository {
#PersistenceContext(unitName = "vivesPU")
private EntityManager entityManager;
public List<Brewer> getAll() {
List<Brewer> brewers = new ArrayList<>();
Brewer br0 = new Brewer("WESTVLETEREN BREWERY");
Brewer br1 = new Brewer("BRASSERIE CANTILLON");
Brewer br2 = new Brewer("RODENBACH BREWERY");
Brewer br3 = new Brewer("KULMINATOR");
Brewer br4 = new Brewer("‘T BRUGS BEERTJE");
brewers.add(br0);
brewers.add(br1);
brewers.add(br2);
brewers.add(br3);
brewers.add(br4);
return brewers;
}
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="vivesPU" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>jdbc/beers</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyTenSevenDialect"/>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
Error log (some of it)
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeController' defined in file [..\HomeController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beerRepository': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'vivesPU' available
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beerRepository': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'vivesPU' available
...
Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'vivesPU' available]]
vivesPU is the persistance-unit name, so why would it even go there?
project structure
Can someone explain to me what is happening? I'm really confused. Most of the documentation and posts are old (Spring 4 and Spring XML) which are barely relevant.
Either you have to autowire BeerRepository or remove the below line
private final BeerRepository beerRepository;
Your controller is completely false. It should be
#Controller
#ComponentScan(basePackages = "org.vives.repositories")
public class HomeController extends HttpServlet {
#Autowired
private BeerRepository beerRepository;
#GetMapping("/")
public String index(Model model) {
List<Brewer> brewers = beerRepository.getAll();
model.addAttribute("brewers", brewers);
return "index";
}
}
Related
I am getting the following error when using the #Transactional annotation. Any ideas?
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myRepository' defined in file [myFile]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class myRepository]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:191)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:636)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at myRepository.main(myRepository.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class myRepository]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:217)
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:111)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:477)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:362)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:409)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1520)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
... 16 more
Caused by: java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given
at org.springframework.cglib.proxy.Enhancer.emitConstructors(Enhancer.java:721)
at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:499)
at org.springframework.cglib.transform.TransformingClassGenerator.generateClass(TransformingClassGenerator.java:33)
at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at org.springframework.cglib.proxy.Enhancer.create(Enhancer.java:285)
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:205)
Code:
#Repository
public class MyRepository {
private MyDao myDao;
#Autowired
public MyRepository(MyDao myDao) {
this.myDao = myDao
}
#Transactional
public void save(Object obj) {
if (obj.isNew())
myDao.create(obj)
}
}
XML:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- Enable Annotation based Declarative Transaction Management -->
<tx:annotation-driven proxy-target-class="true"
transaction-manager="transactionManager" />
<!-- Creating TransactionManager Bean, since JDBC we are creating of type DataSourceTransactionManager -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource"
class="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" >
// datasource settings
</bean>
Superclass has no null constructors but no arguments were given
You need to autowire the field, and either remove the constructor or provide an additional no-argument constructor.
#Repository
public class MyRepository {
#Autowired
private MyDao myDao;
#Transactional
public void save(Object obj) {
if (obj.isNew())
myDao.create(obj)
}
}
}
Alternatively, use a #Transactional interface instead of a class so CGLIB doesn't need to be involved at all.
#Repository
#Transactional
public interface MyRepository {
void save(Object obj);
}
public class MyRepositoryImpl implements MyRepository {
private final MyDao myDao;
#Autowired
public MyRepository(MyDao myDao) {
this.myDao = myDao
}
public void save(Object obj) {
if (obj.isNew())
myDao.create(obj)
}
}
}
I am new new to spring programming.While executing a program for fetching some records from mysql database i am getting these errors:
log4j:WARN No appenders could be found for logger (org.springframework.beans.factory.xml.XmlBeanDefinitionReader).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'edao' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'jtemplate' while setting bean property 'jdbcTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jtemplate' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'ds' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ds' defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.jdbc.Driver]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:104)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1245)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at Test.main(Test.java:15)
I have three files in my project.
1.EmpDAO.java:
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
public class EmpDAO {
private JdbcTemplate template;
public JdbcTemplate getTemplate() {
return template;
}
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Student> getAllStudents(){
return (List<Student>) template.query("select * from test",new ResultSetExtractor(){
#Override
public List<Student> extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<Student> list=new ArrayList<Student>();
while(rs.next()){
Student e=new Student();
e.setName(rs.getString(1));
e.setRoll(rs.getString(2));
list.add(e);
}
return list;
}
});
}
}
2.Student.java:
public class Student {
private String name;
private String roll;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public void display(){
System.out.println("Name: "+name+" Roll="+roll);
}
}
3.applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/test" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
<bean id="jtemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="ds"></constructor-arg>
</bean>
<bean id="edao" class="EmpDAO">
<property name="jdbcTemplate" ref="jtemplate"></property>
</bean>
</beans>
4.Test.java(for execution):
import java.util.List;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);
EmpDAO dao=(EmpDAO)factory.getBean("edao");
List<Student> list=dao.getAllStudents();
for(Student e:list)
System.out.println(e);
}
}
The jars that i included in reference library:
These are the jars i included
Kindly help me in this regards.A prevalentines day thank you is in advance.
The relevant part of your errormessage is:
java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.jdbc.Driver]
You can download that jar from here: 5.1.38, or look for different versions on the central nexus repository.
Note: you would be much better of employing some dependency management system, rather than doing this manually. I suggest taking a look at Maven.
We'd like to test EJB-s in unit tests as Spring components.
The one of the EJB-s using the Resources annotation in order to look up a JNDI values like this:
#Resource(lookup = "java:global/myapp/portal/url")
private String portalUrl;
The problem is that it seems that Spring tries to look up the value by type i.e. it looks for a bean of type java.lang.String in the application context instead of using JNDI.
Here's our code.
1st context:
<bean id="serverMock" class="myapp.JndiServerMock">
</bean>
2nd context:
<context:annotation-config />
<context:component-scan base-package="myapp">
<context:include-filter type="annotation" expression="javax.ejb.Stateless" />
<context:include-filter type="annotation"
expression="javax.annotation.Resources" />
</context:component-scan>
<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor">
<property name="alwaysUseJndiLookup" value="true" />
</bean>
<bean id="clientMock" class="myapp.JndiClientMock">
<bean id="java:global/myapp/portal/url" class="java.lang.String">
<constructor-arg value="http://localhost:8080" type="java.lang.String"/>
</bean>
JndiServerMock:
public class JndiServerMock {
public JndiServerMock() throws IllegalStateException, NamingException {
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
builder.bind("java:global/myapp/portal/url", "http://localhost:8080");
builder.activate();
}
}
JndiClientMock:
public class JndiClientMock {
public JndiClientMock() throws NamingException {
Hashtable<String, String> prop = new Hashtable<String, String>();
prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.springframework.mock.jndi.SimpleNamingContextBuilder");
InitialContext ic = new InitialContext(prop);
System.err.println("result = " + ic.lookup("java:global/myapp/portal/url"));
}
}
ExampleBean:
#Stateless
public class ExampleBean {
#Resource(lookup = "java:global/myapp/portal/url")
private String portalUrl;
public ExampleBean() {
System.err.println("portalUrl = " + portalUrl);
}
}
public class MainApp {
public static void main(String[] args) {
System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.springframework.mock.jndi.SimpleNamingContextBuilder");
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("/spring/firstContext.xml",
"/spring/secondContext.xml");
ExampleBean exampleBean = applicationContext.getBean(ExampleBean.class);
}
}
If the "java:global/myapp/portal/url" bean definition is omitted then the following exception will be thrown:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.annotation.Resource(shareable=true, lookup=java:global/myapp/portal/url, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:457)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:435)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:559)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:305)
... 13 more
I think the problem here is how you're trying to set the JNDI entry in the Spring config - here's an example of how to do this. This provides examples of other ways of achieving the same thing. However, if you're looking to do this for a unit test, I think the JUnit section here is likely to be a neater approach, but it certainly looks like you have lots of options!
I am trying to run a #AspectJ Based AOP with Spring 3.1 & not able to configure pointcut properly
Pointcut and advice methods are :
Pointcuts:
#Pointcut("execution(* point.*.*(..))")
public void selectAll() {}
after advice:
#After("selectAll()")
public void afterAdvice() {
System.out.println("profile has been setup.");
}
before advice:
#Before("selectAll()")
public void beforeAdvice() {
System.out.println("Going to setup profile.");
}
& run main program i got Exception:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'student' defined in class path resource [spring.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut selectAll
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
although when i give pointcut expression in beforeAdvice() and afterAdvice() methods , remove PointCuts method every thing work fine
#Before("execution(* point.*.*(..))")
public void beforeAdvice() {
System.out.println("Going to setup profile.");
}
#After("execution(* point.*.*(..))")
public void afterAdvice() {
System.out.println("profile has been setup.");
}
i am trying to apply pointcut to method of Student class:
package point;
public class Student{
private Integer age;
private String name;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
System.out.println("Age : " + age);
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
System.out.println("Name : " + name);
return name;
}
public void printThrowException() {
System.out.println("Exception raised");
throw new IllegalArgumentException();
}
}
spring configuration xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<aop:aspectj-autoproxy />
<bean id="student" class="point.Student">
<property name="name" value="Zara" />
<property name="age" value="11" />
</bean>
<bean id="logging" class="point.Logging" />
</beans>
Jar file used :
aopalliance-1.0.jar
asm-3.3.1.jar
aspectj-1.7.1.jar
aspectjrt-1.6.8.jar
aspectjtools-1.5.4.jar
aspectjweaver-1.6.2.jar
cglib-2.2.2.jar
with spring 3.1 jar's
solved the problem : The issue while creating bean was because of old jars
Replaced jars:
aopalliance-1.0.jar
asm-3.3.1.jar
aspectj-1.7.1.jar
aspectjrt-1.6.8.jar
aspectjtools-1.5.4.jar
aspectjweaver-1.6.2.jar
cglib-2.2.2.jar
with
aopalliance-1.0.jar
asm-3.3.1.jar
aspectj-1.7.1.jar
aspectjrt-1.7.0.jar
aspectjweaver-1.7.0.jar
cglib-2.2.2.jar
I have 2 classes
public class Abcd{
private String username;
private String password;
public Abcd(#Value("${username}") String userName, #Value("${password}") String password) {
...
}
public String retrieveValues(){
......
return "someString";
}
}
public class SomeClass{
#Autowired
private Abcd obj;
public String method1(){
obj.retrieveValues();
}
I have a Xml as below.
<context:annotation-config />
<context:property-placeholder location="classpath:applNew.properties" />
<bean id="abcd" class="com.somecompany.Abcd">
<constructor-arg type="java.lang.String" value="${prop.user}" />
<constructor-arg type="java.lang.String" value="${prop.password}" />
</bean>
<bean id="someclass"
class="com.differentcompany.SomeClass">
</bean>
When I build the project and start the server, i see the below exceptions.
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'abcd' defined in URL []: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class []: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given
Caused by: java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given
I dont understand what could be the issue to do a constructor injecting this way. Is there any solution for this?
Classes to be proxied by CGLIB (for AOP support) must have no-args constructors.
These no-args constructors don't have to be public and it doesn't affect anything else - you can use other constructors as usually:
public class Abcd{
// Dummy constructor for AOP
Abcd() {}
public Abcd(#Value("${username}") String userName, #Value("${password}") String password) { ... }
...
}
See also:
7.6 Proxying mechanisms