使用@Configurable进行Spring自动装配

opt*_*ude 32 java spring aspectj spring-aop

我正在尝试使用Spring @Configurable并将@AutowireDAO注入域对象,这样他们就不需要直接了解持久层了.

我正在尝试关注http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-atconfigurable,但我的代码似乎没有效果.

基本上,我有:

@Configurable
public class Artist {

    @Autowired
    private ArtistDAO artistDao;

    public void setArtistDao(ArtistDAO artistDao) {
        this.artistDao = artistDao;
    }

    public void save() {
        artistDao.save(this);
    }

}
Run Code Online (Sandbox Code Playgroud)

和:

public interface ArtistDAO {

    public void save(Artist artist);

}
Run Code Online (Sandbox Code Playgroud)

@Component
public class ArtistDAOImpl implements ArtistDAO {

    @Override
    public void save(Artist artist) {
        System.out.println("saving");
    }

}
Run Code Online (Sandbox Code Playgroud)

在application-context.xml中,我有:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springsource.org/dtd/spring-beans-2.0.dtd">
<beans>

    <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />
    <bean class="org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect" factory-method="aspectOf"/>

</beans>
Run Code Online (Sandbox Code Playgroud)

类路径扫描和初始化由弹簧模块执行Play!框架,虽然其他autowired bean工作,所以我很确定这不是根本原因.我正在使用Spring 3.0.5.

在其他代码中(实际上在使用Spring注入我的控制器的bean中的方法内部),我这样做:

Artist artist = new Artist();
artist.save();
Run Code Online (Sandbox Code Playgroud)

这给了我一个NullPointerException试图访问Artist.save()中的artistDao.

知道我做错了什么吗?

马丁

axt*_*avt 9

您需要启用加载时编织(或其他类型的编织)才能使用@Configurable.确保正确启用它,如7.8.4 Spring Framework中使用AspectJ进行加载时编织中所述.

  • @AdamGent他说过LTW(或其他类型的编织)...您需要加载时织入或编译时编织可配置注释. (4认同)

Chr*_*s B 6

我使用LTW尝试将bean自动装入我的域类中时遇到Tomcat 7的这个问题.

有一些更新的文档为3.2.x中在http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/aop.html#aop-configurable-container这表明,可以使用@EnableSpringConfigured而不是xml配置.

所以我在我的Domain对象上有以下注释:

@Configurable(preConstruction=true,dependencyCheck=true,autowire=Autowire.BY_TYPE)
@EnableSpringConfigured
Run Code Online (Sandbox Code Playgroud)

@EnableSpringConfigured是一个替代品

<context:spring-configured />
Run Code Online (Sandbox Code Playgroud)

并且不要忘记将它添加到您的上下文xml文件中:

<context:load-time-weaver weaver-class="org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver" aspectj-weaving="on"/>
Run Code Online (Sandbox Code Playgroud)

当然我需要首先设置Tomcat进行加载时间编织.

另外,我遇​​到了3.2.0中的错误(空指针)所以我需要升级到Spring 3.2.1(https://jira.springsource.org/browse/SPR-10108)

一切都很好!


duf*_*ymo 1

也许使用DAO 的@Repository注释就可以做到这一点。

  • 你能解释一下为什么这会产生影响吗? (5认同)
  • 它如何与“@Configurable”相关? (2认同)