0

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

我不明白可能是什么问题做一个构造函数注入这种方式。有没有解决方案?

+0

你为什么在Abcd的构造函数中传递'@ Value'如果你传递了v通过春天的线索(通过'$ {prop.user}')? – sfat

+0

@AndreiSfat:我试图不传递值,然后我看到另一个异常类似的异常。 – iuser

+0

出于某种原因,你有cglib代理的东西在那里。你能发布完整的spring配置吗? – mbelow

回答

3

要由CGLIB代理的类(用于AOP支持)必须具有无参数构造函数。

这些无参数的构造函数不必是public,它不会影响任何东西 - 你可以使用其他构造函数通常为:

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

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

参见:

+0

为什么在我没有使用它的地方AOP会聚焦。我只是想构造函数注入值。 – iuser

+0

@iuser:也许您使用的功能需要AOP:'@ Transactional','@ Async','@ Cache',安全等。 – axtavt