简体   繁体   中英

Spring dependency injection with static constructors

I have been using Guice for a few years now and just switched to a company that uses Spring. I am a fan of Dependency Injection but having a few issues figuring out how to get Spring to do what I want.

Here is what I have in the code right now (its not scala code, just shorter so using that syntax):

class A(b: B)
class B(exe: ExecutorService)
...
@Value("${search.threads}") var searchThreads: int
exe = Executors.newFixedThreadPool(searchThreads)

In guava I could use Named annotations to have different executors, or just use one executor for anyone that needed it and just define

final int searchThreads = readSearchThreadsFromConfigs()
bind(Executor.class).toInstance(Executors.newFixedThreadPool(searchThreads));

I am not sure how to set this up within Spring. It seems every example I see doesn't really cover generics, nor does it really go over static constructors or being able to "provide" the value.

What is the best way to get similar results to what I had above from Guice? Is there a notion of a "module" like guice and dagger use (other than the xml file, something statically checked)?

EDIT: Here is a bit of the code currently used. It creates the executor within the constructor:

@Autowired
public LogsModule(@Value("${search.threads}") final int searchThreads) {
  searchPool = Executors.newFixedThreadPool(searchThreads);
}

In Spring it's basically the same.

Your example can be rewritten as follows using @Configuration :

@Bean(value = "searchExecutor", destroyMethod = "shutdownNow")
public ExecutorService executorService(Environment env) {
    final int searchThreads = env.getProperty("searchThreads", Integer.class, 3);
    return Executors.newFixedThreadPool(searchThreads));
}

This example uses Environment - you can either add properties from your config to it, or use your config directly instead.

With XML configuration it would be more complex, but you can mix @Configuration with XML.

If you need multiple executors, you can use @Qualifier (or perhaps @Named ) to distinguish between candidates by their bean names:

@Autowired
public LogsModule(@Qualifier("searchExecutor") ExecutorService e) { ... }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM