I General form of annotation injection
Bean class
public class TestBean{ }
Configuration class
@The Configuration annotation marks this class, which indicates that this class is a Spring Configuration class. It will be loaded when loading the Configuration.
@The annotation of Bean indicates that this is a method of injecting Bean, which will inject the following returned Bean into IOC.
//Create a class configuration file @Configuration public class TestConfiguration{ //A Bean is managed by Spring @Bean public TestBean myBean(){ return new TestBean(); } }
Test class
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); TestBean testBean = cotext.getBean("testBean",TestBean.class); System.out.println("testBean = " + testBean);
II Inject beans through construction methods
When generating a Bean instance, we can use the Bean construction method to inject the Bean implementation
Bean class
@Component public class TestBeanConstructor { private AnotherBean anotherBeanConstructor; @Autowired public TeanBeanConstructor(AnotherBean anotherBeanConstructor){ this.anotherBeanConstructor = anotherBeanConstructor; } @Override public String toString() { return "TeanBean{" + "anotherBeanConstructor=" + anotherBeanConstructor + '}'; } }
AnotherBean class
@Component(value="Bean of id,The default is the class name small hump") public class AnotherBean { }
Configuration class
@Configuration @ComponentScan("com.company.annotationbean") public class TestConfiguration{ }
Annotation interpretation
@AutoWired
automatic assembly 🔧
If you specify the id of a Bean when injecting here, you need to use the @ Qualifier annotation.
Annotations can be used in setter methods to automatically connect bean s, such as @ Autowired annotations, containers, a property, or arbitrarily named methods that may have multiple parameters.
There are more detailed explanations with Baidu examples
@Component (default singleton mode)
@Component is called meta annotation. It is the parent class of @ Repository, @ Service, @ Controller, @ Configuration. In theory, @ component can be used to annotate any class that needs to be automatically assembled by Spring. However, each annotation has its own function to distinguish and classify. The Spring document also indicates that other functions may be added to @ Repository, @ Service, @ Controller, @ Configuration annotations in subsequent versions, so it is recommended to use @ component less.
The @ Repository annotation is the tag of any class that satisfies the Repository role or stereotype (also known as a data access object or DAO). One of the uses of this tag is the automatic translation of exceptions, as described in exception translation.
The @ Service annotation is generally used in the Service layer.
The @ Controller annotation is generally used in the class of the Controller layer, and @ RestController inherits @ Controller.
The @ Configuration annotation is generally used to configure the class and the class loaded when the project is started.
@ComponentScan("")
@ComponentScan annotation is generally used in the core configuration class of Spring project or in the startup class of Spring Boot project. The function is to scan @ Component and its subclass annotation classes for Spring container automatic assembly@ By default, the scanned path of ComponentScan is the same level path and subdirectory of the same level path. Therefore, put the startup class of Spring Boot in the root directory and @ ComponentScan can be omitted.
Main attributes:
- value attribute, basePackages attribute
@AliasFor("basePackages") String[] value() default {}; @AliasFor("value") String[] basePackages() default {};
The function of these two values is the same, which is the relationship of mutual aliases. The content is to fill in the path to be scanned. If there is a path, you don't need to write value. There are several ways to write it as follows:
@ComponentScan("com.zh.service") @ComponentScan(value = "com.zh.service") @ComponentScan(value = {"com.zh.dao", "com.zh.service"})
- includeFilters property, excludeFilters property
These two functions are filters. The function of excludeFilters is to eliminate individual classes that do not need to be loaded in the values attribute, while includeFilters is generally used in combination with excludeFilters, that is, several of the classes that need to be removed by excludeFilters. Use includeFilters and add.
For example, suppose you send excludeFilters and exclude all classes annotated with Repository, but one of the classes starting with Stub needs to be used. You can write it like this in the following example.
ComponentScan.Filter[] includeFilters() default {}; ComponentScan.Filter[] excludeFilters() default {};
Filter is the basic object of the filter
@Retention(RetentionPolicy.RUNTIME) @Target({}) public @interface Filter { FilterType type() default FilterType.ANNOTATION; @AliasFor("classes") Class<?>[] value() default {}; @AliasFor("value") Class<?>[] classes() default {}; String[] pattern() default {}; }
FilterType is the type of filter, which can be defined in several ways
public enum FilterType { ANNOTATION, ASSIGNABLE_TYPE, ASPECTJ, REGEX, CUSTOM; private FilterType() { } }
III Inject Bean through set method
We can inject Bean implementation into the set method of an attribute
Bean class
@Component public class TestBeanSet { private AnotherBean anotherBeanSet; @Autowired public void setAnotherBeanSet(AnotherBean anotherBeanSet) { this.anotherBeanSet = anotherBeanSet; } @Override public String toString() { return "TestBeanSet{" + "anotherBeanSet=" + anotherBeanSet + '}'; } }
Configuration class
@Configuration @ComponentScan("com.company.annotationbean") public class TestConfiguration{ }
Test class
ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); TestBean testBean = cotext.getBean("testBean",TestBean.class); System.out.println("testBean = " + testBean);
IV Inject beans through attributes
@Component public class TestBeanProperty { @Autowired private AnotherBean anotherBeanProperty; @Override public String toString() { return "TestBeanProperty{" + "anotherBeanProperty=" + anotherBeanProperty + '}'; } }
It can be assembled automatically through @ AutoWired.
V Inject beans through List
TestBeanList class
@Component public class TestBeanList { private List<String> stringList; @Autowired public void setStringList(List<String> stringList) { this.stringList = stringList; } public List<String> getStringList() { return stringList; } }
TestConfiguration class
@Configuration @ComponentScan("annoBean.annotationbean") public class TestConfiguration { @Bean public List<String> stringList(){ List<String> stringList = new ArrayList<String>(); stringList.add("List-1"); stringList.add("List-2"); return stringList; } }
Here, we inject TestBeanList, and the elements in the List will be injected one by one.
Let's change the injection method
TestConfiguration class
@Bean //This annotation is used to set the priority of Bean injection, which is not necessarily a continuous number @Order(34) public String string1(){ return "String-1"; } @Bean @Order(14) public String string2(){ return "String-2"; }
Injecting the same type as the generic type in the List will automatically match the type. In time, there is no feeling of List here, just the type of String, but it will inject through the Bean of List.
be careful:
The priority of the second method is higher than that of the first. When both exist, if you want to force the first method to be used, you need to specify the id of the Bean.
Vi Inject beans through Map
@Component public class TestBeanMap { private Map<String,Integer> integerMap; public Map<String, Integer> getIntegerMap() { return integerMap; } @Autowired public void setIntegerMap(Map<String, Integer> integerMap) { this.integerMap = integerMap; } } /** *The first way to inject map */ @Bean public Map<String,Integer> integerMap(){ Map<String,Integer> integerMap = new HashMap<String, Integer>(); integerMap.put("map-1",1); integerMap.put("map-2",2); return integerMap; } /** *The second way is to inject map */ @Bean public Integer integer1(){ return 1; } @Bean public Integer integer2(){ return 2; }
Like List, the second priority is higher than the first