iuser
iuser

Reputation: 209

Spring constructor dependency Injection Issues

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?

Upvotes: 0

Views: 3264

Answers (1)

axtavt
axtavt

Reputation: 242686

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:

Upvotes: 3

Related Questions