【Spring】Spring常用注解(下)

Java
277
0
0
2024-06-11
标签   Spring
person.properties
person.nickName=\u5C0F\u674E\u56DB
MainConfigOfPropertyValues


//使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中;加载完外部的配置文件以后使用${}取出配置文件的值
@PropertySource(value={"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {
   
   @Bean
   public Person person(){
      return new Person();
   }

}
IOCTest_PropertyValue
public class IOCTest_PropertyValue {
   AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
   @Test
   public void test01(){
      printBeans(applicationContext);
      System.out.println("=============");
      
      Person person = (Person) applicationContext.getBean("person");
      System.out.println(person);
      
      
      ConfigurableEnvironment environment = applicationContext.getEnvironment();
      String property = environment.getProperty("person.nickName");
      System.out.println(property);
      applicationContext.close();
   }
   
   private void printBeans(AnnotationConfigApplicationContext applicationContext){
      String[] definitionNames = applicationContext.getBeanDefinitionNames();
      for (String name : definitionNames) {
         System.out.println(name);
      }
   }

}
输出


mainConfigOfPropertyValues
person
=============
Person [name=张三, age=18, nickName=小李四]
小李四
自动装配
@Autowired-@Qualifier-@Primary-@Resource-@Inject


@Controller
public class BookController {
   
   @Autowired
   private BookService bookService;

}
@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 + "]";
   }
   

}
//名字默认是类名首字母小写
@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 + "]";
   }
   
   

}
MainConifgOfAutowired


/**
 * 自动装配;
 *        Spring利用依赖注入(DI),完成对IOC容器中中各个组件的依赖关系赋值;
 * 
 * 1)、@Autowired:自动注入:
 *        1)、默认优先按照类型去容器中找对应的组件:applicationContext.getBean(BookDao.class);找到就赋值
 *        2)、如果找到多个相同类型的组件,再将属性的名称作为组件的id去容器中查找
 *                       applicationContext.getBean("bookDao")
 *        3)、@Qualifier("bookDao"):使用@Qualifier指定需要装配的组件的id,而不是使用属性名
 *        4)、自动装配默认一定要将属性赋值好,没有就会报错;
 *           可以使用@Autowired(required=false);
 *        5)、@Primary:让Spring进行自动装配的时候,默认使用首选的bean;
 *              也可以继续使用@Qualifier指定需要装配的bean的名字
 *        BookService{
 *           @Autowired
 *           BookDao  bookDao;
 *        }
 * 
 * 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:解析完成自动装配功能;       
 * 
 * 3)、 @Autowired:构造器,参数,方法,属性;都是从容器中获取参数组件的值
 *        1)、[标注在方法位置]:@Bean+方法参数;参数从容器中获取;默认不写@Autowired效果是一样的;都能自动装配
 *        2)、[标在构造器上]:如果组件只有一个有参构造器,这个有参构造器的@Autowired可以省略,参数位置的组件还是可以自动从容器中获取
 *        3)、放在参数位置:
 			public Boss(@Autowired Car car){
				this.car = car;
				System.out.println("Boss...有参构造器");
			}
 * 
 * 4)、自定义组件想要使用Spring容器底层的一些组件(ApplicationContext,BeanFactory,xxx);
 *        自定义组件实现xxxAware;在创建对象的时候,会调用接口规定的方法注入相关组件;Aware;
 *        把Spring底层一些组件注入到自定义的Bean中;
 *        xxxAware:功能使用xxxProcessor;
 *           ApplicationContextAware==》ApplicationContextAwareProcessor;
 *     
 *        
 * @author lfy
 *
 */
@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;
   }
   
   /**
    * @Bean标注的方法创建对象的时候,方法参数的值默认从容器中获取
    * @param car
    * @return
    */
   @Bean
   public Color color(Car car){
      Color color = new Color();
      color.setCar(car);
      return color;
   }
   

}
IOCTest_Autowired
public class IOCTest_Autowired {
   
   @Test
   public void test01(){
      AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConifgOfAutowired.class);
      
      BookService bookService = applicationContext.getBean(BookService.class);
      System.out.println(bookService);
      
      //BookDao bean = applicationContext.getBean(BookDao.class);
      //System.out.println(bean);
      
      Boss boss = applicationContext.getBean(Boss.class);
      System.out.println(boss);
      Car car = applicationContext.getBean(Car.class);
      System.out.println(car);
      
      Color color = applicationContext.getBean(Color.class);
      System.out.println(color);
      System.out.println(applicationContext);
      applicationContext.close();
   }

}
@Profle
MainConfigOfProfile
/**
 * 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}");
   }

}
dbconfig.properties
db.user=root
db.password=123456
db.driverClass=com.mysql.jdbc.Driver