@Autowired批注返回null [英] @Autowired annotation returns null
问题描述
当我在Spring Framework中进行开发时,我想使用mybatis在特定类上访问数据库,这是有问题的.
When I develop in the Spring Framework, I wanted to get an access to DB using mybatis on the specific class, here is problem.
public class ScheduleManager {
private Scheduler scheduler;
@Autowired
private TriggerService triggerService;
public void doit() {
System.out.println(triggerService);
}
}
在这里,triggerService的值为null.我认为triggerService没有自动接线.
At here, value of triggerService is null. I think triggerService was not autowired.
但是它是自动装配的.
@Controller
public class TestController {
@Autowired
private TriggerService triggerService;
@RequestMapping("/scheduletest")
public String scheduleTest() {
System.out.println(triggerService);
ScheduleManager sm = new ScheduleManager();
sm.doit();
}
}
此代码显示一些不为null的值.
this code print some value not null.
dispatcher-servlet.xml
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.scheduler"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
<property name="contentType" value="text/html;charset=UTF-8"/>
<property name="order" value="0"/>
</bean>
</beans>
TriggerService接口
TriggerService interface
@Service
public interface TriggerService {
public List<Trigger> getAll();
}
为什么会出现此问题?
推荐答案
您可以自己创建ScheduleManager实例:
You create the ScheduleManager instance by yourself:
ScheduleManager sm = new ScheduleManager();
所以Spring不知道这个对象,也不做任何自动装配.要解决此问题,请在 ScheduleManager
中添加 @Component
批注,并将其也注入控制器:
So Spring doesn't know about this object and doesn't do any autowiring.
To resolve this, add the @Component
annotation to ScheduleManager
and let it also inject in the controller:
@Autowired
private ScheduleManager scheduleManager;
这篇关于@Autowired批注返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!