1. @Value assignment and @propertysource load the configuration file

SpEl introduced: www.jianshu.com/p/e0b50053b…

@ the Value assignment

public class Person {
   // use @value;
   //1
   // select * from SpEL; # {}
   ${}; Fetch the value in the configuration file properties (the value in the runtime environment variable)
   @ Value (" zhang ")
   private String name;
   @Value("#{20-2}")
   private Integer age;
  @Value("${person.nickName}")
  privateString nickName; . }Copy the code

@propertysource Loads the configuration file

@PropertySource(value={"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {
	@Bean
	public Person person(a){
		return newPerson(); }}Copy the code

2. @autoWired and @Qualifier and @primary

@autowired: Automatic injection:

By default, a Bean of this type must be registered. If not, an error will be reported. You can use @autowired (required=false); If you find multiple components of the same type, and you look up the name of the property as the component’S ID in the container, @Autowired can tag constructors, parameters, methods, properties that all get the value of the parameter component from the container

  1. Put it in a member variable
@Controller
public class BookController {
   
   @Autowired
   private BookService bookService;
}
Copy the code

This component is not required for automatic injection. If not, the injection will fail and the bookDao will be null

@Service
public class BookService {
   
   @Autowired(required=false)
   private BookDao bookDao;
}
Copy the code
  1. Mark in method position:
  • @bean method parameter; Parameters are taken from the container; If you don’t say @Autowired by default, it’s the same thing; It’s all self-assembly
  • Set method
/ / @ Bean method
    @Bean
    public Color color(Car car){
       Color color = new Color();
       color.setCar(car);
       return color;
    }
/ / set methods
     @Autowired 
    public void setCar(Car car) {
       this.car = car;
    }
Copy the code
  1. Tag constructor: If the component has only one parameter constructor, the @autowired of the parameter constructor can be omitted, and the component at the parameter position can still be automatically fetched from the container
@Autowired 
public Boss(Car car){
   this.car = car;
   System.out.println("Boss... Parameter constructor");
}
Copy the code
  1. Flags on parameters
//case1
public Boss(@Autowired Car car){
   this.car = car;
   System.out.println("Boss... Parameter constructor");
}
//case2
public void setCar(@Autowired Car car) {
   this.car = car;
}
Copy the code

@ Primary:

When registering a component, set its priority. When automatically injecting the Primary key of this type in other classes, select the component with @primary whose @qualifier conflict is preferred. That is, check @qualifier first (” bookDao “) before @primary

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

@ the Qualifier (” bookDao “) :

Using @Qualifier to specify the ID of the component to be assembled requires the bookDao

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

3. @ the Resource and @ Inject

@Resource and @Inject are Java built-in annotations, not unique to Spring. Other IOC tools can also use @Resource:

  • Can implement autowiring function like @autowired; The default is to assemble by component name;
  • @primary is not supported and cannot achieve effects similar to @autowired (Reqiured =false)
@Service
public class BookService {
	@Resource(name="bookDao2")
	private BookDao bookDao;
	
}
Copy the code

Inject @inject: the package that needs to be imported into Javax. Inject Autowired functions the same as @primary, but does not support required=false;

4. @profile registers beans according to the environment

@ Profile:

Specify the environment (production, development, etc.) in which a component can be registered in the container. Without specifying this environment, the component can be registered in any environment

  1. Registered on a configuration class, the configuration class is only valid under the specified environment, that is, beans scanned and configured by the configuration class are registered only under the specified environment
  2. Registered on a method annotated by @bean, the Bean registered by that method will only 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);
      returndataSource; }}Copy the code

How to configure the environment

Method 1. Use the command line dynamic parameters: load -dspring.profiles. active=test in the vm parameter position



Method 2. Code the way to activate an environment

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

   applicationContext.close();
}
Copy the code