I have a class Foo
in package com.example.dao
-
@Component
public class Foo {
public static final String nameAbc = "Abc";
public static final String nameDef = "Def";
public static List<String> getNames() {
return ImmutableList.of(nameAbc, nameDef);
}
// I created this for testing purpose.
// I was testing if maybe Spring needs an instance of class to inject.
public static Foo instance = new Foo();
}
In a Configuration
BeanConfig class I wish to inject a List<Foo>
and perform some operator on it -
@Configuration
public class BeanConfig {
private List<Foo> foos;
@Autowired
public void setFoos(List<Foo> foos) {this.foos = foos;}
@Bean
public Bar bar() {
// using foos in some logic here for creating Bar bean
}
}
I have also tried using @ComponentScan
on BeanConfig
class -
@ComponentScan(basePackages = "com.example.dao")
but class Foo is still not injected as I get an empty list. What exactly is the mistake here?
Update - It came out to be a different issue - some beans in com.example.dao
package did not had default constructors which caused @ComponentScan
to throw an exception while creating their instances. Updating the constructors resolved the issue.
I used Spring Boot to test your code. Please check your configuration
2016-12-21 20:45:36.326 INFO 25224 --- [ main] com.mycompany.app.Application : Started Application in 11.997 seconds (JVM running for 12.861)
Result: [Abc, Def]
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
@Autowired
private Environment env;
private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
@PostConstruct
public void initApplication() throws IOException {
LOGGER.info("Running with Spring profile(s) : {}", env.getActiveProfiles());
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
List<String> list = Foo.getNames();
System.out.println(list);
}
}
It came out to be a different issue - some beans in com.example.dao package did not had default constructors which caused @ComponentScan to throw an exception while creating their instances. Updating the constructors resolved the issue.
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.