我正在尝试使用Spring @Configurable和@Autowire将DAO注入到域对象中,这样它们就不需要直接了解持久层。
我正在尝试使用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);
}
}和:
public interface ArtistDAO {
public void save(Artist artist);
}和
@Component
public class ArtistDAOImpl implements ArtistDAO {
@Override
public void save(Artist artist) {
System.out.println("saving");
}
}在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>类路径扫描和初始化是由spring模块执行的!框架,尽管其他自动连接的bean可以工作,所以我非常确定这不是根本原因。我使用的是Spring 3.0.5。
在其他代码中(实际上,在使用Spring注入到我的控制器的bean中的方法中),我这样做:
Artist artist = new Artist();
artist.save();这给了我一个试图在Artist.save()中访问artistDao的NullPointerException。
知道我做错了什么吗?
马丁
发布于 2011-01-16 12:23:39
您需要启用加载时编织(或其他类型的编织)才能使用@Configurable。确保您正确启用了它,如7.8.4 Load-time weaving with AspectJ in the Spring Framework中所述。
发布于 2013-02-15 00:10:39
我在Tomcat7中遇到了这个问题,使用LTW试图将bean自动绑定到我的域类中。
在http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/aop.html#aop-configurable-container上,3.2.x的文档有一些更新,表明可以使用@EnableSpringConfigured来代替xml配置。
因此,我在Domain对象上有以下注释:
@Configurable(preConstruction=true,dependencyCheck=true,autowire=Autowire.BY_TYPE)
@EnableSpringConfigured@EnableSpringConfigured是
<context:spring-configured />不要忘了将它添加到您的上下文xml文件中:
<context:load-time-weaver weaver-class="org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver" aspectj-weaving="on"/>当然,我首先需要将Tomcat设置为加载时编织。
另外,我在3.2.0中遇到了一个bug (空指针),所以我需要升级到Spring3.2.1 (https://jira.springsource.org/browse/SPR-10108)。
现在一切都好了!
发布于 2011-04-26 22:58:42
首先,启用Spring调试日志记录。我使用Log4j来做这件事。我已经创建了一个日志记录器,如下所示(使用Log4j xml配置,所以我可以使用RollingFileAppender):
<log4j:configuration>
<appender name="roll" class="org.apache.log4j.rolling.RollingFileAppender">
blah blah configuration blah blah
</appender>
<logger name="org.springframework">
<level value="debug" />
<appender-ref ref="roll" />
</logger>
</log4j:configuration>这将允许您看到Spring正在做什么以及什么时候做。
其次,您已经自动连接了ArtistDAO,但是我不知道您在哪里有一个名为ArtistDAO的bean。默认情况下,您的DAO组件bean将命名为"artistDaoImpl“。尝试将@Component更改为@Component("artistDao")并将@Autowired应用于设置器:
private ArtistDAO artistDao;
@Autowired
public void setArtistDao(ArtistDAO artistDao)
{
this.artistDao = artistDao;
}https://stackoverflow.com/questions/4703206
复制相似问题