This is a continuation of About Spring②. This time, I will briefly summarize the bean association.
Which object behaves as a bean in the previous chapter and the chapter before last? We have summarized the specification of and the behavior of the DI container that stores it. In the basic bean injection method, the getBean method was called with the bean class as an argument to the ContextConfiguration class, but how is the bean specified in autowiring using @Autowired? Is it?
Overview → Determine by the type of class specified when using.
Config.class
@Congiguration
@ComponentScan
public class Config{
@Bean
HogeClass hogeClass(){
return new HogeClass();
}
@Bean
FugaClass fugaClass(){
return new FugaClass();
}
}
Injection.class
public class Injection{
@Autowired
HogeClass hogeClass;
@Autowired
FugaClass fugaClass;
}
Bean of the specified type does not exist ⇒ NoSuchBeanDefinitionException occurs
Multiple beans of the specified type are registered in the container ⇒ NoUniqueBeanDefinitionException occurs
In particular, it is often the case that there are multiple classes that inherit a certain parent class in the program, and it is the meaning of DI to write the class of the child class in the source code when doing DI each time. Instead, if you are using a bean in the parent class, a NoUniqueDefinitionException will occur, and so on. The next method is to solve this.
Overview → Set a unique name when defining a bean, and specify that name when retrieving
Config.class
@Congiguration
@ComponentScan
public class Config{
@Bean
HogeClass hogeClass(){
return new HogeClass();
}
@Bean
HogeClass fugaClass(){
return new FugaClass();
}
}
Injection.class
public class Injection{
@Autowired
@Qualifer("hogeClass")
HogeClass hoge;
@Autowired
@Qualifer("fugaClass")
HogeClass fuga;
}
In the above case, both are classes that have HogeClass as a parent, so an error will occur unless they are linked by name by Qualifer. If you want to specify the name individually, do as follows
Config.class
@Congiguration
@ComponentScan
public class Config{
@Bean(name = "hoge1")
HogeClass hogeClass(){
return new HogeClass();
}
@Bean(name = "fuga1")
HogeClass fugaClass(){
return new FugaClass();
}
}
##Next time preview
I want to end the contents of the component scan and the scope of the bean together.
Recommended Posts