20、自动装配(类赋值)-@Autowired&@Qualifier&@Primary
- 自动装配:Spring 利用依赖注入(DI),完成对IOC容器中各个依赖关系赋值
20.1 @Autowired :自动注入
- 优先按照类型去容器中找对应的组件,
applicationContext.getBean(BookRepository.class)
,找到就赋值。 - 如果找到多个相同类型的组件,再将属性名称作为组件的id 去容器中查找
applicationContext.getBean("bookRepository")
@Primary
(加到@Bean注册到容器的类上)让Spring进行自动装配的时候,默认选择需要装配的bean,也可以使用@Qualifier
指定需要装配的bean的名称
- 使用
@Qualifier("bookRepository")
指定装配组件 - 自动装配默认一定要将属性赋值好,没有就会报错。可以使用
@Autowired(required = false)
来配置非必须的注入,有则注入,没有就算了。 @Qualifier
的权重大于 @Primary
,如果指定了@Qualifier
则 @Primary
失效
实例:
![](https://i-blog.csdnimg.cn/blog_migrate/a6b56400beb198a3cbcf931289f6dd72.png)
package com.suirui.springanno.autowiredDemo.Service;
import com.suirui.springanno.autowiredDemo.dao.BookDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class BookService {
@Autowired(required = false)
@Qualifier("bookDao")
private BookDao bookDao2;
public void print(){
System.out.println("BookService bookDao类注入" + bookDao2);
if (bookDao2 == null) {
return;
}
System.out.println("bookDao的Label: " + bookDao2.getLabel());
}
}
package com.suirui.springanno.autowiredDemo.config;
import com.suirui.springanno.autowiredDemo.dao.BookDao;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
@ComponentScan(value = "com.suirui.springanno.autowiredDemo")
public class MainConfigAutoWired {
@Bean(value = "bookDao2")
@Primary
public BookDao bookDao(){
BookDao b = new BookDao();
b.setLabel("2");
return b;
}
}
package com.suirui.springanno.autowiredDemo;
import com.suirui.springanno.autowiredDemo.Service.BookService;
import com.suirui.springanno.autowiredDemo.config.MainConfigAutoWired;
import com.suirui.springanno.propertyValues.entity.Person;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
public class MainTestAutoWired {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(MainConfigAutoWired.class);
String[] beanDefinitionNames = ac.getBeanDefinitionNames();
for (String s : beanDefinitionNames) {
System.out.println(s);
}
BookService bookService = (BookService) ac.getBean("bookService");
bookService.print();
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/5a6dcd50426ffbe7e4222a2d9f194e71.png)