问题描述
当我在 Spring Framework 中开发时,我想在特定类上使用 mybatis 来访问 DB,这是问题.
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 的值为空.我认为 triggerService 不是自动装配的.
At here, value of triggerService is null. I think triggerService was not autowired.
但它是在这个类中自动装配的.
But it is autowired at this class.
@Controller
public class TestController {
@Autowired
private TriggerService triggerService;
@RequestMapping("/scheduletest")
public String scheduleTest() {
System.out.println(triggerService);
ScheduleManager sm = new ScheduleManager();
sm.doit();
}
}
此代码打印一些非空值.
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();
}
为什么会出现这个问题?
Why does this problem appear?
推荐答案
您自己创建 ScheduleManager 实例:
You create the ScheduleManager instance by yourself:
ScheduleManager sm = new ScheduleManager();
所以 Spring 不知道这个对象,也不做任何自动装配.要解决此问题,请将 @Component
注释添加到 ScheduleManager
并让它也注入控制器:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!