spring annotation Driven Development -- attribute assignment

1. @Value assignment and @ PropertySource loading configuration file

SpEl Introduction: https://www.jianshu.com/p/e0b50053b5d3

@Value assignment

public class Person {
   //Use @ Value to assign Value;
   //1. Basic value
   //2. You can write a spiel; ා {}
   //3. You can write ${}; take out the value in the configuration file [properties] (the value in the running environment variable)
   @Value("Zhang San")
   private String name;
   @Value("#{20-2}")
   private Integer age;
  @Value("${person.nickName}")
  private String nickName;
  .....
}

@PropertySource load configuration file

@PropertySource(value={"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {
	@Bean
	public Person person(){
		return new Person();
	}
}

2. @Autowired and @ Qualifier and @ Primary

@Wired: Auto injection:

By default, search for the corresponding component in the container according to the type
Automatic assembly must register this type of Bean by default. If there is no Bean, an error will be reported;
You can use @ Autowired(required=false);
If multiple components of the same type are found, the name of the attribute is used as the id of the component to search in the container
@Autowired can be marked on constructors, parameters, methods, and properties
They all get the value of the parameter component from the container

  1. Put in member variable
@Controller
public class BookController {
   
   @Autowired
   private BookService bookService;
}

This component is not required for automatic injection. If not, the injection fails and bookDao is null

@Service
public class BookService {
   
   @Autowired(required=false)
   private BookDao bookDao;
}
  1. Mark in method position:
  • @Bean method parameters; parameters are obtained from the container; the default is not to write @ Autowired; the effect is the same; can be automatically assembled
  • set method
//@Bean method
    @Bean
    public Color color(Car car){
       Color color = new Color();
       color.setCar(car);
       return color;
    }
//set method
     @Autowired 
    public void setCar(Car car) {
       this.car = car;
    }
  1. Marked on the constructor:
    If the component has only one parameter constructor, the @ Autowired of the parameter constructor can be omitted, and the component with parameter position can be automatically obtained from the container
@Autowired 
public Boss(Car car){
   this.car = car;
   System.out.println("Boss...Parametric constructors");
}
  1. Flag on parameter
//case1
public Boss(@Autowired Car car){
   this.car = car;
   System.out.println("Boss...Parametric constructors");
}
//case2
public void setCar(@Autowired Car car) {
   this.car = car;
}

@Primary:

When registering a component, set its priority. When automatically injecting this type of Primary key in other classes, the component with @ Primary is preferred
Its @ Qualifier conflict is to judge @ Qualifier("bookDao") first and then @ Primary

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

@Qualifier("bookDao"):

Use @ Qualifier to specify the id of the component to be assembled
bookDao required

@Service
public class BookService {
	
	@Qualifier("bookDao")
	@Autowired(required=false)
	private BookDao bookDao;
}

3. @Resource and @ Inject

@Resource and @ Inject are java's own annotations, which are not unique to spring, and can also be used by other ioc tools
@Resource:

  • The automatic assembly function can be realized just like @ Autowired. By default, it is assembled according to the component name;
  • The @ Primary function is not supported and the effect like @ Autowired (required = false) cannot be implemented
@Service
public class BookService {
	@Resource(name="bookDao2")
	private BookDao bookDao;
	
}

@Inject:
Import required javax.inject Bag of
Autowired supports @ Primary, but does not support required=false;

4. @Profile register Bean according to environment

@Profile:

Specify the environment (production environment, development environment, etc.) in which the component can be registered in the container. If not specified, the component can be registered in any environment

  1. If it is registered on the configuration class, the configuration class will only take effect in the specified environment, that is, the beans scanned and configured by this configuration class will only be registered in the specified environment
  2. Registered on the method marked by @ Bean. The Bean registered by this method will be registered under the specified environment
@PropertySource("classpath:/dbconfig.properties")
@Configuration
public class MainConfigOfProfile{
   @Value("${db.user}")
   private String user;
   private StringValueResolver valueResolver;
   private String  driverClass;
   
   @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;
   }

}

How to configure the environment
Method 1. Use command line dynamic parameters: load in the virtual machine parameter location- Dspring.profiles.active=test

Method 2. Activate the environment in the way of code

@Test
public void test01(){
   AnnotationConfigApplicationContext applicationContext = 
         new AnnotationConfigApplicationContext();//The nonparametric constructor is used here
   //1. Create an applicationContext
   //2. Set up the environment that needs to be activated
   applicationContext.getEnvironment().setActiveProfiles("dev");
   //3. Register main configuration class
   applicationContext.register(MainConfigOfProfile.class);
   //4. Start refresh container
   applicationContext.refresh();
      
   String[] namesForType = applicationContext.getBeanNamesForType(DataSource.class);
   for (String string : namesForType) {
      System.out.println(string);
   }

   applicationContext.close();
}

Tags: JDBC MySQL Attribute Java

Posted on Tue, 30 Jun 2020 00:29:28 -0400 by utahcon