Spring annotation - Day3 -- auto injection

Day 3

@Value

@The Value annotation is used to set the Value of the Bean to be injected into the container. There are three ways to use it:

  1. Basic value
  2. You can write SpEL, {}
  3. You can use ${} to get the value in the configuration file (the value in the running environment variable)

To read the configuration file, you need to add @ PropertySource(value = {"classpath:/person.properties"}, encoding = "gbk") annotation above the configuration class to read the configuration file

The specific usage is as follows

@Component
public class Person {
    @Value("32")
    private int age;
    @Value("lym")
    private String name;
    @Value("${nickName}")
    private String nickName;
    //constructor,setter,getter.
}
//nickName is the value whose key is nickName in the read configuration file
@PropertySource(value = {"classpath:/person.properties"},encoding = "gbk")
@Configuration
public class MainConfigPropertyValues {
    @Bean
    public Person person(){
        return new Person();
    }
}

@Autowired

@Simple use of Autowired

This annotation implements automatic injection.

  1. The default priority is to find the corresponding component in the container by type: applicationContext.getBean(BookDao.class);
  2. If more than one type of component is found, the name of the property is used as the component id to search in the container.
  3. @The Qualifier() annotation specifies the component id to be assembled
  4. During automatic assembly, you should add the objects to be assembled into the IOC container, otherwise an error will be reported. You can use @ Autowired(require=false) to remove this restriction
  5. During assembly, @ Primary can be used to specify the default preferred bean for automatic assembly. It cannot coexist with @ Qualifier()

The following is explained by code

//The configuration classes are as follows
@Configuration
@ComponentScan({"com.lym.controller","com.lym.service","com.lym.dao","com.lym.bean"})
public class MainConfigAutowired {
    @Primary
    @Bean(value = "bookDao1")
    public BookDao bookDao(){
        BookDao bookDao = new BookDao();
        bookDao.setLabel("2");
        return bookDao;
    }
}
//The IOC container has two components of BookDao type, one is manually configured, and the other is entered by @ CompomentScan scanning.
@Repository
public class BookDao {
    private String label = "1";
    public String getLabel() 
        return label;

    public void setLabel(String label) 
        this.label = label;
    @Override
    public String toString() {
        return "BookDao{" +
                "label='" + label + '\'' +
                '}';
    }
}
//In the Service, we need the bookDao object. If we follow the current settings, the bean s loaded manually into the IOC container will be injected into the bookDao2 below.
public class BookService {
    //@Qualifier("bookDao")
    //@Autowired(required = false)
    BookDao bookDao2;

    @Override
    public String toString() {
        return "BookService{" +
                "bookDao=" + bookDao2 +
                '}';
    }
}

@Autowired can be labeled above properties, setter methods, or constructors. Parameters in methods in @ Bean in configuration classes can also be obtained from IOC containers when creating objects

//@Autowired(required = false)
BookDao bookDao2;
@Autowired
public void setBookDao2(BookDao bookDao2) {
    this.bookDao2 = bookDao2;
}

@Configuration
@ComponentScan({"com.lym.controller","com.lym.service","com.lym.dao","com.lym.bean"})
public class MainConfigAutowired {
    //The parameters in the method annotated by @ Bean annotation will also look for the corresponding component generation object from the IOC container.
    @Bean
    public Color color(Car car){
        Color color = new Color();
        color.setCar(car);
        return color;
    }
}

@Autowired principle

stay

@Resource and @ Inject

These two annotations have the same function as @ Autowired, but they have some functional deficiencies compared with @ Autowired. See the table below for comparison

@Autowired @Resource @Inject
Annotation attribution Spring java specification java specification
require function Support I won't support it I won't support it
@Primary function Support I won't support it Support
@Quelifier function Support To be tested To be tested

Custom component function extension

If the custom component wants to obtain some components at the bottom of the Spring container, it needs to implement corresponding methods. For example, if the previous Spring's ApplicationContext, it needs to implement the ApplicationContextAware interface. The function of Aware interface is realized by post processor.

@Configuration
public class MainConfigOfProfile implements EmbeddedValueResolverAware {
    private StringValueResolver stringValueResolver;
    private String driver;
    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        this.stringValueResolver = resolver;
        this.driver = stringValueResolver.resolveStringValue("${db.drive}");
    }
}

@Profile

In the process of development, we will design many environments. Spring provides us with the function of dynamically activating and switching a series of components according to the current environment.
We add the @ Profile annotation to the @ Bean method in the configuration class. The annotation specifies the environment in which the component can be registered in the container, and does not specify any environment in which the component can be registered. The annotation can be labeled on either the method or the class file. Only in the specified environment can the annotated class or the Bean represented by the method be registered Load

There are two ways to specify an environment:

  1. Specifying the environment with command line arguments
  2. Specifying the environment by code
// 1. You can specify by - Dspring.profiles.active=test
// 2
public void test01(){
    AnnotationConfigApplicationContext applicationContext =
            new AnnotationConfigApplicationContext();
    applicationContext.getEnvironment().setActiveProfiles("dev");
    applicationContext.register(MainConfigOfProfile.class);
    applicationContext.refresh();
    String[] namesForType = applicationContext.getBeanNamesForType(DataSource.class);
    for(String s : namesForType) System.out.println(s);
}
Published 36 original articles, won praise 0, visited 732
Private letter follow

Tags: Spring encoding Java

Posted on Mon, 09 Mar 2020 22:40:01 -0700 by Jamesm