spring自动装配

@Autowired&@Qualifier&@Primary

自动装配;
Spring利用依赖注入(DI),完成对IOC容器中中各个组件的依赖关系赋值;
1)、@Autowired:自动注入

  1. 默认优先按照类型去容器中找对应的组件:applicationContext.getBean(BookDao.class);找到就赋值
  2. 如果找到多个相同类型的组件,再将属性的名称作为组件的id去容器中查找 applicationContext.getBean(“bookDao”)
  3. @Qualifier(“bookDao”):使用@Qualifier指定需要装配的组件的id,而不是使用属性名
  4. 自动装配默认一定要将属性赋值好,没有就会报错;可以使用@Autowired(required=false);表示忽略当前要注入的bean,如果有直接注入,没有跳过,不会报错。
  5. @Primary:让Spring进行自动装配的时候,默认使用首选的bean;也可以继续使用@Qualifier指定需要装配的bean的名字

2)、Spring还支持使用@Resource(JSR250)和@Inject(JSR330)[java规范的注解]
@Resource:
可以和@Autowired一样实现自动装配功能;默认是按照组件名称进行装配的;
没有能支持@Primary功能没有支持@Autowired(reqiured=false);
@Inject:
需要导入javax.inject的包,和Autowired的功能一样。没有required=false的功能;
@Autowired:Spring定义的; @Resource、@Inject都是java规范
AutowiredAnnotationBeanPostProcessor:解析完成自动装配功能;

//默认加在ioc容器中的组件,容器启动会调用无参构造器创建对象,再进行初始化赋值等操作
@Component
public class Boss {
  private Car car;
 
  //构造器要用的组件,都是从容器中获取
  public Boss(Car car){
     this.car = car;
     System.out.println("Boss...有参构造器");
  }
  
  public Car getCar() {
     return car;
  }
  //@Autowired 
  //标注在方法,Spring容器创建当前对象,就会调用方法,完成赋值;
  //方法使用的参数,自定义类型的值从ioc容器中获取
  public void setCar(Car car) {
     this.car = car;
  }
  @Override
  public String toString() {
     return "Boss [car=" + car + "]";
  }
}

//名字默认是类名首字母小写
@Repository
public class BookDao {
  private String lable = "1";
  public String getLable() {
     return lable;
  }
  public void setLable(String lable) {
     this.lable = lable;
  }
  @Override
  public String toString() {
     return "BookDao [lable=" + lable + "]";
  }
}

@Service
public class BookService {
  //@Qualifier("bookDao")
  //@Autowired(required=false)
  //@Resource(name="bookDao2")
  @Inject
  private BookDao bookDao;
  
  public void print(){
     System.out.println(bookDao);
  }
 
  @Override
  public String toString() {
     return "BookService [bookDao=" + bookDao + "]";
  }
}

@Configuration
@ComponentScan({"com.atguigu.service","com.atguigu.dao","com.atguigu.controller","com.atguigu.bean"})
public class MainConifgOfAutowired {
  @Primary
  @Bean("bookDao2")
  public BookDao bookDao(){
     BookDao bookDao = new BookDao();
     bookDao.setLable("2");
     return bookDao;
  }
}

3)、 @Autowired:构造器,参数,方法,属性;都是从容器中获取参数组件的值

  1. [标注在方法位置]:@Bean+方法参数;参数从容器中获取;默认不写@Autowired效果是一样的;都能自动装配
  2. [标在构造器上]:如果组件只有一个有参构造器,这个有参构造器的@Autowired可以省略,参数位置的组件还是可以自动从容器中获取
  3. 放在参数位置:
@Configuration
@ComponentScan({"com.atguigu.service","com.atguigu.dao",
  "com.atguigu.controller","com.atguigu.bean"})
public class MainConifgOfAutowired {
  
  /**
   * @Bean标注的方法创建对象的时候,方法参数的值从容器中获取
   * @param car
   * @return
   */
  @Bean
  public Color color(Car car){
     Color color = new Color();
     color.setCar(car);
     return color;
  }
}

@Profile环境搭建
dbconfig.properties

db.user=root
db.password=123456
db.driverClass=com.mysql.jdbc.Driver
/**
 * Profile:
 *     Spring为我们提供的可以根据当前环境,动态的激活和切换一系列组件的功能;
 * 开发环境、测试环境、生产环境;
 * 数据源:(/A)(/B)(/C);
 * @Profile:指定组件在哪个环境的情况下才能被注册到容器中,不指定,任何环境下都能注册这个组件
 * 1)、加了环境标识的bean,只有这个环境被激活的时候才能注册到容器中。默认是default环境
 * 2)、写在配置类上,只有是指定的环境的时候,整个配置类里面的所有配置才能开始生效
 * 3)、没有标注环境标识的bean在,任何环境下都是加载的;
 */
@PropertySource("classpath:/dbconfig.properties")
@Configuration
public class MainConfigOfProfile implements EmbeddedValueResolverAware{
  
  @Value("${db.user}")
  private String user;
  private StringValueResolver valueResolver;
  private String  driverClass;
  
  @Bean
  public Yellow yellow(){
     return new Yellow();
  }
  
  @Profile("test")
  @Bean("testDataSource")
  public DataSource dataSourceTest(@Value("${db.password}")String pwd) throws Exception{
     ComboPooledDataSource dataSource = new ComboPooledDataSource();
     dataSource.setUser(user);
     dataSource.setPassword(pwd);
     dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
     dataSource.setDriverClass(driverClass);
     return dataSource;
  }
  
  
  @Profile("dev")
  @Bean("devDataSource")
  public DataSource dataSourceDev(@Value("${db.password}")String pwd) throws Exception{
     ComboPooledDataSource dataSource = new ComboPooledDataSource();
     dataSource.setUser(user);
     dataSource.setPassword(pwd);
     dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/ssm_crud");
     dataSource.setDriverClass(driverClass);
     return dataSource;
  }
  
  @Profile("prod")
  @Bean("prodDataSource")
  public DataSource dataSourceProd(@Value("${db.password}")String pwd) throws Exception{
     ComboPooledDataSource dataSource = new ComboPooledDataSource();
     dataSource.setUser(user);
     dataSource.setPassword(pwd);
     dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/scw_0515");
     
     dataSource.setDriverClass(driverClass);
     return dataSource;
  }
 
  @Override
  public void setEmbeddedValueResolver(StringValueResolver resolver) {
     // TODO Auto-generated method stub
     this.valueResolver = resolver;
     driverClass = valueResolver.resolveStringValue("${db.driverClass}");
  }
}

public class IOCTest_Profile {
  //1、使用命令行动态参数: 在虚拟机参数位置加载 -Dspring.profiles.active=test
  //2、代码的方式激活某种环境;
  @Test
  public void test01(){
     AnnotationConfigApplicationContext applicationContext = 
          new AnnotationConfigApplicationContext();
     //1、创建一个applicationContext
     //2、设置需要激活的环境
     applicationContext.getEnvironment().setActiveProfiles("dev");
     //3、注册主配置类
     applicationContext.register(MainConfigOfProfile.class);
     //4、启动刷新容器
     applicationContext.refresh();
     String[] namesForType = applicationContext.getBeanNamesForType(DataSource.class);
     for (String string : namesForType) {
       System.out.println(string);
     }
     Yellow bean = applicationContext.getBean(Yellow.class);
     System.out.println(bean);
     applicationContext.close();
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值