I have a class which extends Thread. Each thread connects to own HTTP server.
How to configure Spring Bean and to pass custom domain for each thread?
As far as I know Spring supports such scopes: singleton, prototype, session, request.
You can inject a list of threads based on the properties. something like this:
The thread class.
public class MyThread implements Runnable{
private String domain;
public MyThread(String domain) {
this.domain = domain;
}
@Override
public void run() {
System.out.println(domain);
}
}
The property file:
t1.domain=www.domain1.com
t2.domain=www.domain2.com
The config class:
@Configuration
@PropertySource(value="classpath:test.properties", name="testProperties")
public class Config {
@Autowired
private Environment env;
@Bean
public List<MyThread> myThreads(){
List<MyThread> list = new ArrayList<>();
for(Iterator it = ((AbstractEnvironment) env).getPropertySources().iterator(); it.hasNext(); ) {
org.springframework.core.env.PropertySource propertySource = (org.springframework.core.env.PropertySource) it.next();
if ("testProperties".equals(propertySource.getName())) {
for(String propertyName : ((MapPropertySource) propertySource).getPropertyNames()){
list.add(new MyThread(propertySource.getProperty(propertyName).toString()));
}
}
}
return list;
}
}
The class that uses the threads:
List<MyThread> ll = (List<MyThread>)context.getBean("myThreads");
for(MyThread t : ll){
Thread th = new Thread(t);
th.start();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.