spring注解开发-03

@Autowired、@Resource、@Inject

@Autowired

	 @Autowired默认是按照类型装配,当要调用的接口存在多个实现类时,
     * 1、要注入容器的名称与注册到IOC的容器名称保持一致;
     * 2、使用@Qualifier("...")指定需要导入的容器
     * 3、使用@Primary注解把容器当中的接口实现指定为主要的

@Resource和@Inject

 /**
     * @Resource: 默认按照属性名称去IOC容器进行查找对应的bean组件,也可以指定name属性,找到属性值对应的bean,
     *              没有@Primary也没有require=false
     * @Inject:
     *   首先需要引入inject的坐标,默认按照属性名称去查找对应的bean组件,可以使用@Primary,不可以在@Inject注解上
     *   指定任何的属性。
     * @Resource和@Inject的共同点:都是java的,而@Autowired是spring的
     */
  • @Inject导入的包是:

      		
      			javax.inject
      			javax.inject
      			1
      		
    

@Autowired不仅能做属性注入、还可以做方法注入、构造器注入、参数注入等

  • Car Bean:

      @Component
      public class Car {
      
          /**
           * 颜色
           */
          private String color;
      
          public String getColor() {
              return color;
          }
      
          public void setColor(String color) {
              this.color = color;
          }
      
          public Car() {
          }
      
          public Car(String color) {
              this.color = color;
          }
      }
    

属性注入:在属性上添加@Autowired注解,自动会去IOC容器中去查找对应的bean组件

@Component
public class Boss {

	@Autowired
    private Car car;

    @Override
    public String toString() {
        return "Boss{" +
                "car=" + car +
                '}';
    }
}

方法注入:在方法上添加@Autowired注解,自动会去IOC容器中去查找对应的bean组件

@Component
public class Boss {


    private Car car;

    public Car getCar() {
        return car;
    }

	@Autowired
    public void setCar(Car car) {
        this.car = car;
    }

    @Override
    public String toString() {
        return "Boss{" +
                "car=" + car +
                '}';
    }
}

构造方法注入:在构造方法上添加注解,自动会去IOC容器中去查找对应的bean组件,如果一个对象中有且只有一个有参构造,注解可省略

@Component
public class Boss {


    private Car car;

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

	@Autowired
    public Boss( Car car) {
        this.car = car;
    }

    @Override
    public String toString() {
        return "Boss{" +
                "car=" + car +
                '}';
    }
}

参数注入:在参数上添加@Autowired注解,自动会去IOC容器中去查找对应的bean组件,如果一个对象中有且只有一个有参构造,注解可省略

@Component
	public class Boss {
	
	
	    private Car car;
	
	    public Car getCar() {
	        return car;
	    }
	
	    public void setCar(Car car) {
	        this.car = car;
	    }
	
		
	    public Boss( @Autowired Car car) {
	        this.car = car;
	    }
	
	    @Override
	    public String toString() {
	        return "Boss{" +
	                "car=" + car +
	                '}';
	    }
	}

Aware源码

 /* 
 		1、首先执行的是前置拦截器postProcessBeforeInitialization(),判断bean是不是属于这些具体的Aware实现类:
         * if (System.getSecurityManager() != null &&
         * 				(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
         * 						bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
         * 						bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
         * 			acc = this.applicationContext.getBeanFactory().getAccessControlContext();
         *                }
         *  2、如果access不为空,那么判断对应的权限
         *  if (acc != null) {
         * 			AccessController.doPrivileged(new PrivilegedAction() {
         *                                @Override
         * 				public Object run() {
         * 					invokeAwareInterfaces(bean);
         * 					return null;
         * 				}
         * 			}, acc);
         * 		}
         *  3、对属性进行实例化并进行赋值
         *  private void invokeAwareInterfaces(Object bean) {
         * 		if (bean instanceof Aware) {
         * 			if (bean instanceof EnvironmentAware) {
         * 				((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
         * 			}
         * 			if (bean instanceof EmbeddedValueResolverAware) {
         * 				((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
         * 			}
         * 			if (bean instanceof ResourceLoaderAware) {
         * 				((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
         * 			}
         * 			if (bean instanceof ApplicationEventPublisherAware) {
         * 				((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
         * 			}
         * 			if (bean instanceof MessageSourceAware) {
         * 				((MessageSourceAware) bean).setMessageSource(this.applicationContext);
         * 			}
         * 			if (bean instanceof ApplicationContextAware) {
         * 				((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
         * 			}
         * 		}
         * 	}
         *
         */
 
  

Profile多环境

  • 导包

      
      			com.mchange
      			c3p0
      			0.9.5.1
      		
      
      		
      			mysql
      			mysql-connector-java
      			5.1.32
      		
    
  • 准备一个Configration类:

      @Configuration
      public class ConfigrationByProfiles {
      
          @Profile("dev")
          @Bean
          public DataSource dataSourceByDev(){
              DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
              driverManagerDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/tensquare_user?characterEncoding=utf-8");
              driverManagerDataSource.setDriverClass("com.mysql.jdbc,Driver");
              driverManagerDataSource.setUser("root");
              driverManagerDataSource.setPassword("root");
              return driverManagerDataSource;
          }
      
          @Profile("test")
          @Bean
          public DataSource dataSourceByTest(){
              DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
              driverManagerDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/tensquare_qa?characterEncoding=utf-8");
              driverManagerDataSource.setDriverClass("com.mysql.jdbc,Driver");
              driverManagerDataSource.setUser("root");
              driverManagerDataSource.setPassword("root");
              return driverManagerDataSource;
          }
      
          @Profile("prod")
          @Bean
          public DataSource dataSourceByProd(){
              DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
              driverManagerDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/tensquare_gathering?characterEncoding=utf-8");
              driverManagerDataSource.setDriverClass("com.mysql.jdbc,Driver");
              driverManagerDataSource.setUser("root");
              driverManagerDataSource.setPassword("root");
              return driverManagerDataSource;
          }
      
      }
    

1、改变JVM的运行环境

  • 设置JVM的参数:

      -Dspring.profiles.active=dev
    

2、设置使用环境的状态

		/**
		this();//初始化
		register(annotatedClasses);//注册配置
		refresh();//刷新context
		*/
		//获取一个配置类
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        //初始化一个环境变量
        ConfigurableEnvironment configurableEnvironment = new StandardEnvironment();
        //设置默认执行的环境
        configurableEnvironment.setDefaultProfiles("dev");
        //设置需要执行的环境
        configurableEnvironment.setActiveProfiles("dev");
        //将环境进行重新设置
        context.setEnvironment(configurableEnvironment);
        //将配置类进行注册
        context.register(ConfigrationByProfiles.class);
        //context刷新
        context.refresh();
        //获取环境标识并设置对应的环境
        String[] beanDefinitionNames = context.getBeanDefinitionNames();
        for(String beanDefinitionName : beanDefinitionNames){
            System.out.println(beanDefinitionName);
        }

你可能感兴趣的:(spring注解开发)