Spring构造函数依赖注入问题

时间:2012-12-04 20:30:22

标签: spring dependency-injection annotations autowired constructor-injection

我有2个班级

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();
}

我有一个Xml如下。

<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>

当我构建项目并启动服务器时,我会看到以下例外情况。

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

我不明白用这种方式注入构造函数可能是什么问题。对此有什么解决方案吗?

1 个答案:

答案 0 :(得分:3)

CGLIB代理的类(对于AOP支持)必须具有no-args构造函数。

这些no-args构造函数不必是public,它不会影响其他任何东西 - 你可以像往常一样使用其他构造函数:

public class Abcd{
    // Dummy constructor for AOP
    Abcd() {}

    public Abcd(@Value("${username}") String userName, @Value("${password}") String password) { ... }   
    ...
}

另见: