我有一个守护,可它需要插入数据到数据库.不知道怎样注入Bean服务,所以目前是这样的:
public static void main(String[] args) {
Thread daemon=new Thread(new DaemonRun());
daemon.setDaemon(true);
daemon.start();
SpringApplication.run(Application.class, args);
}
....
public class DaemonRun implements Runnable {
private DataService dataService;
public synchronized DataService getDataService(){
if(dataService==null)
dataService=(DataService)SpringApplicationContextHolder.getSpringBean("dataService");
return dataService;
}
有没有办法让DataService 自动注入DaemonRun同时DaemonRun又开机运行在一个独立线程里呢?
天蓬老师2017-04-18 10:50:11
Sorry everyone, I found a way myself.: http://stackoverflow.com/ques...
According to the answer, change it to
@Component
class ThreadRun implements DisposableBean.... Then start the thread in the structure, close the thread in destroy, and you can use automatic injection
ringa_lee2017-04-18 10:50:11
You mean you want to automatically inject the beans of the interface, right? You can refer to spring's injection of abstract class beans or interface objects
Create an abstract class DataService implements Runnable for injection. Then extend it.
Because the life cycle of springbean is completed when the beanFactory is created, your object needs to be injected only when it is created, which conflicts with the concept of spring.
The following is taken from stackoverflow,
Mark the abstract base class definition as abstract by using the abstract attribute , and in the concrete class definition , make the parent attribute be the name of the abstract class 's bean name
Something like this:
<bean id="abstractBaseClass" abstract="true" class="pacakge1.AbstractBaseClass">
<property name="mailserver" value="DefaultMailServer"/>
</bean>
<bean id="concreteClass1" class="pacakge1.ConcreteClass1" parent="abstractBaseClass">
<!--Override the value of the abstract based class if necessary-->
<property name="mailserver" value="AnotherMailServer"/>
</bean>