[英]Problems with @Autowire annotation
In my Class A, I'm auto-wiring Class B which has @Service annotation. 在我的A类中,我正在自动装配具有@Service批注的B类。 In my Class B I'm auto-wiring class C and using reference to that class inside @Transactional method in class B. 在我的B类中,我正在自动装配C类,并在B类中的@Transactional方法内使用对该类的引用。
And it appears that Auto-Wiring didn't do anything because I get java.lang.NullPointerException
而且似乎自动接线没有任何作用,因为我得到了java.lang.NullPointerException
Example of Class A : A类示例:
@Controller
public Class controller{
@Autowired
private MyService myservice;
}
Class B B级
@Service
public Class serviceImpl{
@Autowired
private DAOInterface dao;
//nullpointer
@Transactional
public String getItem(){
return dao.getItem(2);
}
}
Any Help? 有帮助吗?
If you want to use the @Autowired
annotation to do your Spring wiring for you, you need to register the proper BeanPostProcessor
's to assist. 如果要使用@Autowired
注释为您进行Spring接线,则需要注册适当的BeanPostProcessor
来提供帮助。 You can have Spring do this for you by including the following element in your Spring configuration: 您可以让Spring通过在Spring配置中包含以下元素来为您完成此操作:
<context:annotation-config/>
Take a look at Section 3.9 in the Spring 3.0 Documentation for more information on this. 有关更多信息,请参阅Spring 3.0文档中的3.9节 。
Also, since it appears that you are using the stereotype annotations ( @Component
, @Service
, @Controller
), you may be trying to forego Spring XML wiring (or reducing it). 另外,由于似乎您使用的是@Component
型注释( @Component
, @Service
@Controller
, @Service
@Controller
),因此您可能正在尝试放弃Spring XML接线(或减少接线)。 You will need to make sure that you are including the component-scan element in your Spring XML. 您将需要确保在Spring XML中包括component-scan元素。
NOTE: If you are including component-scan
, then you should not need to use the annotation-config
element. 注意:如果要包含component-scan
,则无需使用annotation-config
元素。
<context:component-scan base-package="your.package.name"/>
Take a look at Section 3.10 in the Spring 3.0 Documentation for more information on this. 有关更多信息,请参阅Spring 3.0文档中的3.10节 。
Make sure you're DAO is configured in some way...whether it be with an annotation (@Service, @Component, @Repository), in the xml configuration, or through some other means. 确保以某种方式配置了DAO ...无论是使用xml配置中的注解(@ Service,@ Component,@ Repository),还是通过其他方式进行配置。
If this doesn't help, we will need more information. 如果这样做没有帮助,我们将需要更多信息。
Service Class 服务等级
@Service
public Class serviceImpl implements MyService {
@Autowired
private DAOInterface dao;
//nullpointer
@Transactional
public String getItem(){
return dao.getItem(2);
}
}
spring-servlet.xml spring-servlet.xml
<context:annotation-config/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.