`
>>Spring elementary notes
1. Corresponding annotation of Bean label in configuration file
1.1 configure package scanning
<!--Package scanning Spring To scan the annotations in this package and its subpackages, include@Component And so on --> <context:component-scan base-package="Package name">
one 2@Component annotation
1.2.1 function and basic use
Function: replacement Spring In the configuration file<bean id= class= >label Usage: @Component public class User{ } id The default value of is lowercase class Gets the full class name by reflection
Code examples
@Component public class User { private Integer id; private String name; private String password; }
test
@Test public void test1(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); //The default id is lowercase User user = (User) applicationContext.getBean("user"); //The object created by the factory is obtained through the test System.out.println(user); }
1.2.2 annotation source code
@Target(ElementType.TYPE) //Indicates that this annotation can only be annotated on class interface enumeration classes @Retention(RetentionPolicy.RUNTIME) @Documented @Indexed public @interface Component { String value() default ""; //The value attribute is an id attribute that can be customized for the object } @Component("custom id") public class User { private Integer id; private String name; private String password; }
1.2.3 use configuration file to override annotation configuration content
If both the annotation and the configuration file are used, the configuration file will override the annotation, provided that the id attribute of the configuration in the configuration file is the same as that of the annotation. If the id is different, Spring will create different objects
1.2.4@Component Derived annotation
@Repository ----Used in xxxDAO Implementation class (Not used, DAO Interface implementation classes are Mybatis What did you do) @Service ----Used in xxxServieImpl upper @Controller ----Used in xxxController upper In essence, these derivative annotations are@Component Objective: to express the function of a class more accurately@Component equally
one 3@Scope annotation
Controls the number of times an object is created, similar to the scope property in a bean tag
<bean id="" class="" scope="singleton/prototype"></bean>
Usage
@Component @Scope(value = "prototype/singleton") //The default is singleton public class User { private Integer id; private String name; private String password; }
one 4@Lazy annotation
Control the loading time of the object. The bean with the default scope of singleton is created when the Spring factory is created. You can set the @ lazy annotation to set lazy loading.
@Component //true means to turn on lazy loading, and false means to turn off lazy loading, which is only valid for singleton beans @Lazy(value = true/false) public class User { private Integer id; private String name; private String password; }
one 5@Component Annotation summary
- 1. Can only be annotated on a class annotation enumeration class
- 2. It is equivalent to the bean tag in the Spring configuration file
- 3. Derived annotation @ Repository @Service @Controller
- 4. The id class name of the assigned default bean is not shown in lowercase
2. Notes on the life cycle of Bean
2.1 overview of bean life cycle review
conduct Bean The initialization of the Spring Prescribed InitializingBean Interface to implement its specified method, or custom method in bean Configuration in label init-method Property to use this method Using annotation development, you only need to use it in the custom initialization method of this class@PostConstruct Annotation is enough conduct Bean The destruction of the system should be realized Spring Prescribed DisposableBean Interface and implement its methods, or custom methods in bean Configuration in label destoty-method Property to specify this method (Note: destruction is only for singleton It is only valid when the plant is closed) Using annotation development, you only need to use it on the custom destroy method of this class@PreDestory Annotation is enough
two 2@PostConstruct initialization
@Component public class User { private Integer id; private String name; private String password; @PostConstruct public void myInit(){ } }
two 3@PreDestory Destruction
@Component public class User { private Integer id; private String name; private String password; @PreDestroy public void myDestory(){ } }
3. Notes on attribute injection
three 1@Autowired Annotation (custom type)
3.1.1 retrospective injection
Injection essentially calls the set method to assign values to it
Profile injection encoding
public class UserDaoImpl implements UserDao { @Override public void query() { System.out.println("Called query method"); } }
public class UserServiceImpl implements UserService { private UserDao userDao; public UserDao getUserDao() { return userDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public void select() { } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="userDao" class="com.shwsh.dao.UserDaoImpl"></bean> <bean id="userService" class="com.shwsh.service.UserServiceImpl"> <!--What is called here is UserServiceImpl Class set Method, using userDao Object to assign a value to it--> <property name="userDao" ref="userDao"></property> </bean> </beans>
3.1.2 using @ Autowired annotation
Note: the @ Autowired annotation is injected according to the attribute type in the class. That is to say, you annotate the @ Autowired annotation, and then Spring will find the corresponding type of object in the factory to inject according to the type of your set method (which can be the interface implementation class or its subclass)
@Service public class UserServiceImpl implements UserService { private UserDao userDao; public UserDao getUserDao() { return userDao; } //Annotated in the set method, find the implementation class object of the corresponding UserDao interface in the factory, and then call the set method to achieve injection. @Autowired public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public void select() { } }
@Repository public class UserDaoImpl implements UserDao { @Override public void query() { System.out.println("Called query method"); } }
3.1.3 using @ Qualifier annotation and @ Autowired to implement id based attribute injection
@Repository("userDao") public class UserDaoImpl implements UserDao { @Override public void query() { System.out.println("Called query method"); } }
@Service("userService") public class UserServiceImpl implements UserService { private UserDao userDao; public UserDao getUserDao() { return userDao; } @Autowired //The attribute here must be consistent with the id attribute of the corresponding bean, that is, the specified id injection should also be used with the @ Autowired attribute @Qualifier("userDao") public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public void select() { userDao.query(); } }
3.1.4@Autowired Another place to use annotations is to mark them directly on attributes
If it is marked on attributes, Spring directly assigns values to member variables through reflection
@Service("userService") public class UserServiceImpl implements UserService { //Spring gets the attribute through reflection and assigns it a value directly without calling the set method, //@Qualifier() can also be directly marked on attributes, which is the same as marking on methods. It gets bean s according to id attributes @Autowired @Qualifier("userDao") private UserDao userDao; @Override public void select() { userDao.query(); } }
3.1.5@Resource Annotation and @ Inject annotation
@Resource wrong Spring The comments provided are JavaEE The annotation provided by the specification, which can be based on type or id Property should be@Resource Of value Property is assigned a value(That is to say, a bean Of id attribute),It's based on id Property is injected. If it is not assigned a value, it is injected based on the type @Inject Is based on the type of injection, commonly used with EJB3.0,To introduce its dependencies javax.inject
3.1.6 summary of injection types
1. It can be annotated on set method or attribute directly
2. If the annotation is on the set method, Spring will directly call the set method to inject attributes
3. If it is annotated directly on an attribute, Spring will get the attribute directly through reflection, and then inject it
4. @ Autowired is injected based on type, which can be combined with @ Qualifier("bean id") to inject based on id attribute
5. When the @ Resource does not specify the value attribute, it is injected based on the type. If the id value is specified, it is injected based on the id
3.2 JDK type injection
3.2.1@Value How to use notes
1,use xx.properties with kv The form of 2,stay Spring This configuration file is introduced into the configuration file of use<context:property-placeholder location=""/> 3,use@Value The annotation is directly marked on the corresponding attribute and used ${key}Assign a value to it,
3.2.2@Value summary
- Cannot assign a value to a static property
- Cannot assign a value to a collection type
3.2.2@PropertySource annotation
Function: replace the label of introducing external properties configuration file into Spring configuration file in the second step of injection process
Development steps after replacement
1,use xx.properties with kv The form of 2,application@PropertySource(value="xx.properties route"),Label on class 3,use@Value The annotation is directly marked on the corresponding attribute and used ${key}Assign a value to it,
4. Detailed explanation of annotation scanning
4.1 scan review
<context:component-scan base-package="com.xx"/> By default, the current package and its subpackages are scanned
4.2 exclusion strategy
<context:component-scan base-package="com.baizhiedu"> <context:exclude-filter type="" expression=""/> type:assignable:Exclude specific types from scanning annotation:Exclude specific annotations from scanning aspectj:Pointcut expression (common) Package entry point: com.baizhiedu.bean..* Class entry point: *..User regex:regular expression custom: Development of custom exclusion policy framework </context:component-scan> The exclusion strategy can be superimposed <context:component-scan base-package="com.baizhiedu"> <context:exclude-filter type="assignable" expression="com.baizhiedu.bean.User"/> <context:exclude-filter type="aspectj" expression="com.baizhiedu.injection..*"/> </context:component-scan>
4.3 inclusion strategy
<context:component-scan base-package="com.baizhiedu" use-default-filters="false"> <context:include-filter type="" expression=""/> </context:component-scan> 1. use-default-filters="false" Function: let Spring The default annotation scan mode is invalid. 2. <context:include-filter type="" expression=""/> Function: specifies which annotations to scan type:assignable:Exclude specific types from scanning annotation:Exclude specific annotations from scanning aspectj:Pointcut expression Package entry point: com.baizhiedu.bean..* Class entry point: *..User regex:regular expression custom: Development of custom exclusion policy framework The method of inclusion supports superposition <context:component-scan base-package="com.baizhiedu" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan>
5. Other details of notes
Spring annotations and configuration files are interoperable, that is, beans configured with annotations can be referenced in configuration files, and beans configured in configuration files can also be used in classes
When do I need to use annotations and configuration files?
We can use annotations for our custom classes, such as UserServiceImpl,UserCotroller etc. We also have to use the configuration file for the classes that are not developed by us and provided by the third-party framework(So far),For example, in front of our integration Mybatis,Third party jar Package provides us with two core classes, SqlSessionFactoryBean(establish Mybatis In SqlSessionFactory)as well as MapperScannerConfigure(For our Dao Interface to generate proxy class objects),Like these classes, we have to use configuration files
>>Spring advanced annotation (3.x and above)
6. @ configuration annotation
6.1 overview and basic use
- Function: completely replace the Spring Configuration file applicationContext.xml, that is, as long as there is a class with @ Configuration annotation, then this class is equivalent to a Spring applicationContext Configuration file
- It is also a derivative annotation of @ Component
Note: in use Spring The configuration file of our factory is ClassPathXmlApplication,And we use@Configurantion When annotating, what you want to get the factory to use is AnnotationConfigApplicationContext This class
Creating factories with annotations
@Configuration public class MyConfig { }
Get factory
@Test public void test2(){ ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class); //Get the factory and pass in the configuration class object directly. Multiple configuration classes can be passed in //The second way to get the Configuration factory is to pass in the package name. Spring automatically scans all @ Configuration classes under this package and its subpackages ApplicationContext context1 = new AnnotationConfigApplicationContext("com.shwsh"); } }
6.2 simple principle (Cglib agent)
The principle of configuration class is proxy mode. Cglib proxy is used to create a proxy mode for configuration class and add additional functions for its @ Bean method, including (number of object creation, etc.)
7.@Bean annotation
7.1 overview
It must be used in the class marked with @ Configuration, which is equivalent to bean tags in applicationContext.xml
7.2.1 creation and details of simple object & complex object
- The default method name is the id attribute of the bean, and the return value of the method is the class attribute of the bean. The method body can directly write the object creation process
- You can customize the id of the bean and directly customize the id value -- > @ bean ("id") in the value attribute of the bean tag
- You can use @ Scope("singleton/prototype") to control the number of times an object is created. The default is singleton
@Configuration public class MyConfig { ----Simple object creation //By default, the method name user is the id property of the bean, and the return value is the class property @Bean("u") //Custom id attribute public User user() { return new User(); } ----Creation of complex objects //The method name is the id property of the bean, and the return value is the class property @Bean @Scope("prototype") //Controls the number of times an object is created public Connection conn() { Connection connection = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("xxx", "xx", "xx"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); } return connection; } }
7.2.2 attribute injection based on @ Bean annotation
7.2.2.1 injection of custom type
There are two ways
@Bean public A a() { return new A(); } //The first way is to declare the A directly in the parameters of the method, and then call the set method to assign. @Bean("b1") public B b(A a) { B b = new B(); b.setA(a); return b; } //The second way is to call a method directly to inject it @Bean("b2") public B b() { B b = new B(); b.setA(a()); return b; }
7.2.2.2 JDK type injection
Based on the injection of JDK type, you can directly assign values when creating objects inside the creation method
@Bean public User user() { User user = new User(); user.setId(1); user.setName("xdsa"); return user; }
8.@ComponentScan annotation
8.1 general
- Function: to replace the< context:component-scan >Label, scan the specified annotation
- Usage: used in the Configuration class marked with @ Configuration
8.2 basic use
@Configuration //Scan the annotations under the specified package and its subpackages (the created object, the created object, the injected Injection...) @ComponentScan(basePackages = "com.shwsh") public class MyConfig { }
8.2 scan exclusion and inclusion
exclude
<context:component-scan base-package="com.baizhiedu"> <context:exclude-filter type="assignable" expression="com.baizhiedu.bean.User"/> </context:component-scan> @ComponentScan(basePackages = "com.baizhiedu.scan", excludeFilters = {@ComponentScan.Filter(type= FilterType.ANNOTATION,value={Service.class}), @ComponentScan.Filter(type= FilterType.ASPECTJ,pattern = "*..User1")}) ----corresponding type = FilterType.ANNOTATION value .ASSIGNABLE_TYPE value .ASPECTJ pattern .REGEX pattern .CUSTOM value
contain
<context:component-scan base-package="com.baizhiedu" use-default-filters="false"> <context:include-filter type="" expression=""/> </context:component-scan> @ComponentScan(basePackages = "com.baizhiedu.scan", //Set not to use the Default scan policy, only scan the specified useDefaultFilters = false, includeFilters = {@ComponentScan.Filter(type= FilterType.ANNOTATION,value={Service.class})}) ---corresponding type = FilterType.ANNOTATION value .ASSIGNABLE_TYPE value .ASPECTJ pattern .REGEX pattern .CUSTOM value
9. Summary of the use of advanced notes
Spring Of applicationContext.xml Profile, in SpringBoot It has been completely abandoned and replaced by annotation in the development of. Let's see what annotation has been replaced in the core part of configuration pricing ------------------------------------------------------------------------------ That is to see a person who has been@Configuration Annotated class, treat it as a Spring Of applicationContext.xml configuration file applciationContext.xml ----> @Configuration <bean id = "" class="" scope="" lazy-init=""> ----> @Bean + @Scope + @Lazy <context:component-scan base-package="com.shwsh"> ----->@ComponentScan() <context:property-placeholder location="" /> ----> @PropertySource() ${}assignment ----@Value("${key}") .... <---------------------------------------------------------------------------> @Component And its derived annotations are also replaced in the configuration file Bean Label, due to@Component You need to configure package scanning, so if you want these annotations to work, you must configure package scanning and use@ComponentScan()Annotate or configure package scanning in the configuration file <---------------------------------------------------------------------------> @Autowired The annotation is in the annotation@Component And its derived annotation for property injection, according to the type injection, combination@Qualifier Annotations can be based on id Property injection and stay@Configuration Annotation of configuration class@Bean What do you want in the method bean Assignment, JDK Type direct call set Method, the injection of custom type directly calls the corresponding bean Create the method or declare it in the parameters of the method, and then Spring Automatic injection according to type (Reference 7.2.2) <---------------------------------------------------------------------------> So@Autowired(@Resource)With@Component And its derived annotations(It must have a packet scan to work) @Configuration+@Bean+@ComponentScan()+@PropertySource()+..Use together
10. Multiple configuration methods and integration of Spring Factory creation objects
10.1 application scenarios of various configuration modes and @ Import
1,Spring Of applicationContext.xml It is not used in the development process of pure annotation 2,@Component+Packet scanning Configuration for custom types, such as UserService UserController 3,@Configuration+@Bean Classes provided by the framework for third parties, as SqlSessionFactoryBean MapperSacnnerConfigure 4,@Configuration+@Import Imports the specified type of Bean @Import(xxx.class) We basically don't use it, Spring The bottom layer is widely used
10.2Spring priority of multiple object creation methods
Multiple configurations can work at the same time(ensure id It can't be the same),However, the configuration with higher priority can override the configuration with lower priority (Premise of coverage: id I want the same) Priority from low to high @Component Notes on its derivation< @Bean < Configuration file bean label
10.3 integration among multiple configurations
10.3.1 integrating Spring configuration file with configuration class (@ ImportResource)
Just use @ ImportResource("configuration file location") on the configuration class
Code examples
@Configuration @ImportResource("Spring Location of the configuration file") //Integrate Spring's configuration files into this factory public class MyConfig { }
10.3.2 integration between configuration classes
The first way
Generally, all configuration classes are created in one package, so you can scan the package directly when you create the factory
ApplicationContext c = new AnnotationApplicationContext("com.shwsh.config");
The second way
Use @ Import annotation to Import other configuration classes
@Import is equivalent to the < import tag in the Spring configuration file, which integrates other configuration files, because in the end, Spring will only create a factory,
@Configuration @ComponentScan(basePackages = "com.shwsh") @Import(OtherConfig.class) @Import(OtherConfig1.class) ... public class MyConfig { }
10.3.3 integration of configuration class with @ Component and its derived annotation
Add @ ComponentScan annotation to the configuration class for annotation scanning
@ComponentScan("com.shwsh") @Configuration public class MyConfig{ @Bean ... }
10.4 injection after integration
- After integrating all the configurations, if you want to inject them, you can directly use @ Autowired annotation
- Or you can directly specify multiple configuration classes when creating a factory, so that you can use @ Autowired injection without integrating configuration classes
@Configuration @Import(MyConfig2.class) public class MyConfig1{ //After integrating all the configurations, you can directly use @ Autowired @Autowired private B b; @Bean public A a(){ A a = new A(); a.setB(b); retuen a; } } @Configuration public class MyConfig2{ @Bean public B b(){ B b = new B(); return b; } }
10.5 integration and injection summary
Integration summary
- The configuration class is integrated with the configuration file, and the @ importresource (configuration file location) annotation is used
- The configuration class is integrated with @ Component and its derived annotation and scanned with @ componentscan (specified package) annotation
- For the integration between configuration classes, use @ import (configuration class. class) annotation
Injection only needs to be done after the integration (or specify the package scanning configuration class when creating the factory), and only needs to use @ Autowired annotation injection
11. Four dimensional integration
No matter what labels or annotations we configure, they are ultimately implemented by using the underlying corresponding processing classes. For example, we introduce an external properties configuration file, whether it is used in the Spring configuration file< context:property-placeholder location= "/ > or use the annotation @ PropertySource to introduce. The underlying layer is implemented by using the PropertySourcePlaceConfigure class
12. Annotated AOP
12.1 coding
1. Original object @Service(@Component) public class UserServiceImpl implements UserService{ } 2. Create section class (extra function pointcut assembly section) @Aspect @Component public class MyAspect { @Around("execution(* login(..))") public Object arround(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("----aspect log ------"); Object ret = joinPoint.proceed(); return ret; } } 3. Spring The open annotation is declared in the configuration file of AOP <aop:aspectj-autoproxy /> Label on configuration class @EnableAspectjAutoProxy annotation
12.2 switching agent settings
1. Switching of proxy creation mode JDK Cglib <aop:aspectj-autoproxy proxy-target-class=true|false /> @EnableAspectjAutoProxy(proxyTargetClass=) 2. SpringBoot AOP The way of development @EnableAspectjAutoProxy It's set up 1. Original object @Service(@Component) public class UserServiceImpl implements UserService{ } 2. Create section class (extra function pointcut assembly section) @Aspect @Component public class MyAspect { @Around("execution(* login(..))") public Object arround(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("----aspect log ------"); Object ret = joinPoint.proceed(); return ret; } } Spring AOP Proxy default implementation JDK SpringBOOT AOP Proxy default implementation Cglib
13. Annotated Spring integrates Mybatis
13.1 integration review
1,data source(Connection pool) use DataSource 2,SqlSessionFactoryBean Used to create S(Inject the necessary attribute data source for it mapper File scan entity alias) 3,MapperScannerConfigure(establish Dao Proxy implementation class for) Used to create Dao Proxy class object, configure scan dao Interface and inject it SqlSessionFactoryBean
13.2 coding
@Configuration //Extract the configuration of the database from the outside and use @ PropertySource to introduce it @PropertySource("classpath:db.properties") //Instead of MapperScannerConfigurer, the annotation provided by Spring will automatically scan and inject SqlSessionFactoryBean. You only need to configure dao interface @MapperScan(basePackages = "com.shwsh.dao") public class MybatisConfig { //Inject the configuration in the database configuration file @Value("${user}") private String username; @Value("${password") private String password; @Value("${url}") private String url; @Value("${driver}") private String driver; //Configure data sources @Bean public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUsername(username); dataSource.setDriverClassName(driver); dataSource.setPassword(password); dataSource.setUrl(url); return dataSource; } //Configure SqlSessionFactoryBean @Bean public SqlSessionFacto SqlSessionFactoryBean salSessionFactoryBean() { SqlSessionFactoryBean salSessionFactoryBean = new SqlSessionFactoryBean(); //Injection data source salSessionFactoryBean.setDataSource(dataSource()); //Set the package of the entity class salSessionFactoryBean.setTypeAliasesPackage("com.shwsh.entity"); //Scan mapper.xml file location // factoryBean.setMapperLocations(new ClassPathResource("")); //General matching method of scanning mapper file ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resolver.getResources("classpath:mapper/*Mapper.xml"); sqlSessionFactoryBean.setMapperLocations(resources) return salSessionFactoryBean; } This MapperScannerConfigurer configuration is replaced by the @ MapperScan annotation provided by Spring /* @Bean public MapperScannerConfigurer mapperScannerConfigurer(){ MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setSqlSessionFactoryBeanName("salSessionFactoryBean"); mapperScannerConfigurer.setBasePackage("com.shwsh.entity"); return mapperScannerConfigurer; }*/ }
14. Annotated Spring transactions
14.1 coding review
1,Original object 2,Additional features(DataSourceTransactionManager) 3,Pointcuts and configure transaction properties(@Transactional(islation="",...)) 4,Integrated section using label<tx:annotation-driven trasaction-manager="">
14.2 annotation based
//2. Additional features @Configuration //4. The integration aspect uses @ EnableTransactionManagement annotation to automatically scan DataSourceTransactionManager and pointcut @ Transactional annotation for assembly @EnableTransactionManagement public class TransactionalConfig { //Inject DataSource of other configuration files. Here, @ Import is not used to Import other configuration classes. When you create a factory, you can scan all configuration classes directly @Autowired DataSource dataSource; //Configure DataSourceTransactionManager @Bean public DataSourceTransactionManager dataSourceTransactionManager(){ DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); return transactionManager; } }