Start from P151 November 26, 2021 01:05:39
https://cdn.jsdelivr.net/gh/gwbiubiu/images/20210711093946.png
CHAPTER I BASIC CONCEPTS OF NOTES1. What is annotation programming?
Refers to the addition of a specific comment to a class or method (@XXX),Complete the development of specific functions. @Component public class XXX{}
2. Why explain annotation programming
1. Notes are easy to develop Simple code, much faster development 2. Spring Trends in Development Spring 2.x Introduce notes Spring 3.x Perfect annotations SpringBoot Popularize annotation programming.
3. Role of Notes
- Replace XML as a configuration form to simplify configuration
- Replace interface to achieve contract between caller and caller
1. Annotation is used to reach an agreement between the caller and provider of the function to invoke the function. Because annotation is more convenient and flexible, it is more recommended to use annotation in real-world development.
4. The history of Spirng notes
- Spirng2.x started supporting annotation programming@Component @Service @Scope
Purpose: These annotations are provided only to simplify the configuration of XML in some cases as a useful complement to XML - Spring3.x @Configuration @Bean
Purpose: To completely replace XML, based on pure annotation programming - Spirng4.x SpringBoot
Promote common development with annotations
5. A problem with Spring annotation development
-
Can Spring be decoupled after it has been configured based on annotations?
-
When applying annotations to the Spring framework, if you are not satisfied with the content of the annotation configuration, you can override it with the Spring configuration file.
- Annotations at this stage simply simplify the configuration of XML and do not completely replace it.
- Set up development environment
<context:component-scan base-package="com.jun"/> Role: Let Spring The framework sets annotations for the package and its subpackage scans to take effect.
1. Object Creation Comment@Component
Role: Replacement Spring In the configuration file Bean Label Be careful: id attribute component Annotations provide the default setting, which is lower case for the first letter of a word class Attributes, obtained by reflection class content
- Testing: introducing Junit test units
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
@Test public void test1(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("/SpringContext.xml"); User user = (User) ctx.getBean("user"); System.out.println("user+"+user); }
1-1. @Component annotation usage details
- How to display the id value of the specified factory creation object
@Component("u") //At this point the id value of the User object is no longer a user
- Spring Profile Override Annotation Configuration Content
applicationContext.xml <bean id = "u" class = "com.gewei.bean.User" /> # The value of id and class should be consistent with the settings in the annotations so that overwriting can be achieved. If the value of id is inconsistent, a new object will be created and overwriting cannot be achieved.
2 @Component Derived Annotation
@Repository --> XXXDAO @Service @Controller Note: Essentially these derived notes are@Component Fully consistent role, details and usage Purpose: To more accurately express a type of role. Spring integration Mybatis Not applicable during development@Repository and Component. because spring integration mybatis During the process, do not write XXXDAO Class, DAO Objects are also created by MapperScannerConfigurer Created dynamically for us.
2-1@Scope Controlling the number of times a simple object is created
Role: Controls the number of times a simple object is created Note: Do not add@Scope Spring The default value provided is singleton <bean id=" " class = " " scope = "single|prototype"/>
@Component //Specify the default id value, lowercase the first word of the class name @Scope("singleton") public class Customer { }
@Test public void test2() { ApplicationContext ctx = new ClassPathXmlApplicationContext("/SpringContext.xml"); Customer user1 = (Customer) ctx.getBean("customer"); Customer user2 = (Customer) ctx.getBean("customer"); System.out.println("customer+" + user1); System.out.println("customer+" + user2); }
- Result:
customer+com.gewei.scope.Customer@78a773fd customer+com.gewei.scope.Customer@78a773fd
2-2 @Lazy Delay Creating Single Instance Objects
- Lifecycle: For single-instance objects, spring creates this object by default while the factory is being created
Role: Delay creation of single instance objects <bean id = " " class = " " lazy = "false"/>
@Component public class Account { public Account(){ System.out.println("Account.account"); } }
@Test public void test3(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("/SpringContext.xml"); //The spring factory was created on behalf of }
output
Account.account
- By default, the Spring factory creates objects that need to be loaded directly. If we want to defer the creation of single-instance objects, we can use the @Lazy annotation directly here and go back to creating objects when they are needed.
@Component @Lazy public class Account { public Account(){ System.out.println("Account.account"); } } @Test public void test3(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("/SpringContext.xml"); Account account = (Account) ctx.getBean("account"); //Create the object when used }
3 Comments on Life Cycle Approach
1. Initialize related methods @PostConstruct Interfaces must be implemented when initialization definitions were originally made InitalizingBean Or defined in the label<bean init-method = "" /> 2. destroy-method @PreDestroy Implement Interface DisposableBean Or defined in the label<bean destory-method = ""/> Note: 1.The two notes above are not Spring Provided by, but by JSR520(JavaEE Standard)Provided. 2.Again, the contract of the interface is implemented through annotations.
- Both @PostConstruct and @PreDestroy are in the javax.annotation package, an extension package for java.
<dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.3.2</version> </dependency>
@Component public class Product { @PostConstruct public void myInit(){ System.out.println("Product.myInit"); } @PreDestroy public void myDestory(){ //This method is called only when the factory is closed System.out.println("Product.Destory"); } }
@Test public void test4(){ ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/SpringContext.xml"); ctx.close(); //Closing for factories }
Product.myInit Product.Destory
4. Injection-related notes
- Injection of user-defined type: @Autowired
- JDK Type
4-1@Autowire
Traditional profile development
Development based on annotations
@Repository public class UserDaoImpl implements UserDao{ @Override public void save() { System.out.println("UserDao.Impl"); } }
@Service public class UserServiceImpl implements UserService{ private UserDao userDao; public UserDao getUserDao() { return userDao; } @Autowired public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public void register() { userDao.save(); } }
@Test public void test5() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/SpringContext.xml"); UserService userServiceImpl = (UserService) ctx.getBean("userServiceImpl"); userServiceImpl.register(); }
- Question: @Autowired annotation is injected into the corresponding member variable (userDAO). We will release the annotation on the corresponding set method, and Spring will help us find the corresponding DAO (UserDAOImpl). If there are two DAO implementation classes, such as UserDAOImpl, ProductDAOImpl; How can I ensure that only UserDAO is injected at this point? Instead of injecting ProductDAO?
- Type-based injection:
- Name-based injection: The id value of the injected object must be the same as the name set in the Qualifier comment.
@AutoWired details 1.AutoWired Annotation injection based on type Type-based injection: The type of the injected object must be the same as the type of the target member variable or its subclass (implementation class) 2.AutoWired Coordination Qualifier Annotations are injected based on name Injected object id Value must match Qualifier The same name is set in the comment @Autowired @Qualifier("userDaoImpl") public void setUserDao(UserDao userDao) { this.userDao = userDao; } 3.@AutoWried Note Free Placement a) Placed on the corresponding member variable set Methodologically b) Place this comment directly on the member variable. Spring Injecting member variables directly through reflection (no calls made) set Method) [Recommended] 4. JavaEE Notes for similar functionality in the specification JSR 250 @Resource(name = "userDaoImpl") Name-based injection @Autowired @Qualifier("userDaoImpl") Note: In use Resource If no name pairing succeeds with this comment, the type injection will continue JSR330 @Inject Effect@Autowired Exactly the same, type-based injection [rarely used, commonly used in EJB3.0 Medium, know it) <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency>
4-2@Value
- How JDK type member variables are developed during injection:
Create the init.properties file and place it in the resource directory
id = 24 name = gewei
Configure under the configuration file SpringContext.xml file:
<context:property-placeholder location="classpath:init.properties"/>
@Conponent public class Category{ @Value("$") private Integer id; @Value("$") private String name; } //test @Test public void test1(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); Category category = (Category)ctx.getBean("category"); System.out.println("category.getId() = " + category.getId()); }
@propertySource
- Role: Replaced the <context:property-placeholder location="classpath:init.properties"/>tag in spring
@Component @PropertySource("classpath:/init.properties") public class Category {}@Value Usage Details
@Value Not applicable to static member variables If applied(assignment)On a static member variable, the injection fails @Value+properties In this way, the collection type cannot be injected here Spring A new form of configuration is provided. YAML or YML Perform collection injection (applied to SpringBoot Medium)
5 Annotation Scan Details
- Question: How does the spring framework scan for corresponding annotations?
- <context:component-scan base-package="com.jun"/>For the current package and its subpackages (exclusion or inclusion is provided if you do not want to scan for some comments in the package)
1. Exclusion Method
<context:component-scan base-package="com.gewei"> <context:exclude-filter type="" expression=""/> </context:component-scan> spring Of type Five exclusion methods are provided, one for each 1.assignable: Exclude specific types from scanning <context:component-scan base-package="com.gewei"> <context:exclude-filter type="assignable" expression="com.gewei.bean.User"/> </context:component-scan> 2.anntation: Exclude specific comments from scanning <context:component-scan base-package="com.gewei"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan> 3.aspectj: Entry point expression [more used in development] <context:exclude-filter type="aspectj" expression="com.gewei.bean..*"/> //bean packages and their subpackages Package entry point: com.gewei.bean..* Class entry point:*..User 4.regex: regular expression 5.custom: Custom exclusion strategies are commonly used in the low-level development of frameworks. [Note: Exclusion strategies can be used overlapping] <context:component-scan base-package="com.jun"> <context:exclude-filter type="assignable" expression="com.jun.bean.User"/> <context:exclude-filter type="aspectj" expression="com.jun.injection..*"/> </context:component-scan>
- Test Exclusion Policy
@Test public void test1(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); String[] beanDefinitionNames = ctx.getBeanDefinitionNames(); for(String beanDefinitionName : beanDefinitionNames){ System.out.println("beanDefinitionName = " + beanDefinitionName); } }
2. Inclusion Method
<context:component-scan base-package="com.gewei" use-default-filters="false"> //Invalidate Spring's Default scan mode <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/> //Role: Specify which annotations to scan </context:component-scan> [Note: Included policies can also be used overlay]
6. Reflections on Note Development
- Configure Interoperability
Spring Annotate configuration interacts with configuration file @Repository public class UserDAOImpl{} public class UserServiceImpl{ private UserDAO userDAO; set; get; } <bean id = "userService" class = "com.gewei.UserServiceImpl" <property name = "userDAO" ref = "userDAOImpl"/> //The id value during the reference process is referenced according to the id value set by the @Repository comment </bean>
- Question: Under what circumstances do annotations and configuration files be used?
- On the type of programmer development, you can add corresponding annotations to create objects
- When applied to other types that are not developed by programmers, you still need to configure <bean>. For example: SqlSessionFactoryBean,MapperScannerConfigurer
1. Configure Bean
1.Spring At 3.x A comment provided to replace XML Configuration file. @Configuration public class Appconfig{}
1. What exactly did the configuration bean s replace the XML in the application process?
- AnnotationConfigApplicationContext
- Create factory code: AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
- Specify a configuration file (two ways):
- Specify the class of the configuration bean: AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
- Specify the path where the configuration bean s are located (how packages are scanned):
Detailed Analysis of Configuration Bean Development
- Annotation-based development usage log
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> Development with annotations, not integration log4j,More inclined to use newer technologies; for example: logback org.slf4j Log facets are retained.
- Using logback to introduce related jar packages
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.logback-extensions</groupId> <artifactId>logback-ext-spring</artifactId> <version>0.1.4</version> </dependency>
- Introduce the logback configuration file: logback.xml, set level="DEBUG", or switch to:INFO later
<?xml version="1.0" encoding="UTF-8"?> <configuration> <!-- console output --> <appender name="STDOUT"> <encoder> <!--Format output:%d Indicates the date,%thread Represents the thread name,%-5level: Level shows 5 character width from left%msg: Log messages,%n Is a line break--> <pattern>%d [%thread] %-5level %logger - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="STDOUT" /> </root> </configuration>
- The essence of the @Configuration annotation: @Configuration is also a derived annotation of @Component, which can also be scanned using <context:component-scan.
2.@Bean comment
- The @Bean annotation is used in beans and is equivalent to the <bean tag in the XML configuration file
2-1@Bean Basic use of notes
- Object Creation
- Simple Objects: Objects created directly in a new way. For example, User, UserService
- Complex Objects: Objects cannot be created in a new way. For example, Connection, SqlSessionFactory
- Create complex objects: cannot be created directly by new.
@Bean public Connection conn(){ Connection conn = null; try{ class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://locolhost:3306/suns?useSSL=false,"root","123456"); }catch(ClassNotFoundException e){ e.printStackTrace(); }catch(SQLException e){ e.printStackTrace(); } return conn; }
- Creating complex objects in Spring is often done in a way that implements FactoryBean
public class ConnectionFactoryBean implements FactoryBean<Connection> { @Override public Connection getObject() throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://locolhost:3306/suns?useSSL=false","root","root"); return conn; } @Override public Class<?> getObjectType() { return Connection.class; } @Override public boolean isSingleton() { return false; } }
- Here we can do this in the configuration class. (P178 didn't understand)
@Configuration public class AppConfig{ //1. Simple objects @Bean public User user(){ return new User(); } //2. Create complex objects @Bean public Connection conn(){ Connection conn = null; try{ Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://locolhost:3306/suns?useSSL=false","root","root"); } catch(Exception e){ e.printStackTrace(); } return conn; } //3. How @Bean and FactoryBean are integrated: [Legacy systems are more common] @Bean public Connection conn1(){ ConnectionFactoryBean factoryBean = new ConnectionFactoryBean(); Connection conn = null; try { conn = factoryBean.getObject(); } catch (Exception e) { e.printStackTrace(); } return conn; } }
-
Custom id value
- Note: The method name of the @Bean comment is the id value of the bean (if we want to customize the id value, we just need to name it in @Bean("u").
-
Control number of object creation
<bean id="user" scope="prototype"/> @Configuration public class AppConfig{ @Bean("u") @Scope("prototype") Default value is singleton public User user() } //test @Test public void test3(){ ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); User u = (User)ctx.getBean("U"); User u1 = (User)ctx.getBean("u"); System.out.println("u1 = " + u1); System.out.println("u = " + u); }
Injection of 2-2.@Bean comment
Injection of self-built type@Configuration public class AppConfig { @Bean public UserDao userDao(){ return new UserDaoImpl(); } @Bean public UserService userService(UserDao userDao){ UserServiceImpl userService = new UserServiceImpl(); userService.setUserDao(userDao); return userService; } } //Test: @Test public void test3() { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); UserService userService = (UserService) ctx.getBean("userService"); userService.register(); }
- There's also a simplified way to write it (there's no need to use userDao as a parameter)
@Bean public UserService userService(){ UserServiceImpl userService = new UserServiceImpl(); userService.setUserDao(userDao()); return userService; }Injection of type JDK Detailed analysis of JDK type injection
Create init.properties first, then read the init.properties file inside the configuration class
If done directly in code set Method invocation, there will be coupling problems @Configuration @PropertySource("classpath:/init.properties") public class AppConfig { @Value("$") private Integer id; @Value("$") private String name; @Bean public Customer customer(){ Customer customer = new Customer(); customer.setId(id); customer.setName(name); return customer; } }
3.@ComponentScan comment
@ComponentScan Notes in Configuration bean Used, equivalent to XML In the file<context:component-scan>Label Purpose: Scanning for related annotations (@Component @Value @Autowired)
//Configuration of XML: <context:component-scan base-package="com.jun"/> @Configuration @PropertySource("classpath:/init.properties") //Scan for classes with @Component annotations under the com.jun.scan package @ComponentScan(basePackages = "com.jun.scan") public class AppConfig {}
3-1 Exclusion and Inclusion Related
- Exclude
- Contain
4. Multiple configurations of Spring factory creation objects
4-1 Scenarios for Multiple Configurations
4-2. Configuration Priority
-
@Component and its derived annotations < @Bean <Profile bean tag:
- A configuration with a higher priority may override a configuration with a lower priority. [Configuration override: id values must be consistent]
-
Question: In a note-based development environment, how do I integrate Spring's configuration files with the Spring framework and import them?
- Original integration method: new ClassPathXmlApplicationContext("applicationContext.xml");
- Annotation-based factory: ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); parameter is the class of the configuration Bean. A new annotation @ImportResource(""applicationContext.xml") is introduced at this time.
//Contents in the applicationContext.xml configuration file based on annotation development: <bean id="user"> <property name="id" value="2"/> <property name="name" value="zhangsan"/> </bean> Learn a new note here @Configuration @ComponentScan(basePackages="com.jun.bean") @ImportResource("applicationContext.xml") public class AppConfig{ @Bean public User user(){ User user = new User(); user.setId(1); user.setName("zhangsan"); return user; } } // With this annotation, we can configure it in the applicationContext.xml configuration file, and only import annotation class files into the code. //Test: @Test public void test1(){ ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); User user = (User)ctx.getBean("user"); System.out.println("user.getId() = "+ user.getId()); }
- In this way, we can also solve the coupling problem in the configuration beans by simply overwriting: (P190 doesn't understand)
# Consider a question here. Although the code in the class has not been modified in the configuration Bean, adding a new annotation @ImportResource to the Bean is not a coupling? To solve this problem, we can create a new configuration Bean,Then add it@ImportResource Annotations are then loaded during the loading of the configuration file ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig1.class, AppConfig2.class); Or: ApplicationContext ctx = new AnnotationConfigApplicationContext("com.jun"); //All under the com.jun package are APPConfigx.class
//To not modify the original configuration (AppConfig1) information, redeclare a configuration for APPConfig2 @Configuration @ImportResource("SpringContext.xml") public class AppConfig2 { }
4-3 Integrating multiple configuration information
- If we only configure beans in one file, there could be thousands of lines of code in that file, which is not easy to maintain, so we split it up.
- Why are there multiple configuration information?
- The development of splitting up multiple configuration bean s is a form of modular development, which also reflects the design idea of each department in object-oriented.
- Integration of multiple configuration beans
- Integration of multiple configuration beans
- Configure the integration of Bean and @Component related annotations
- Configuration Bean and Spring.xml Configuration File Integration
- What are the key points to focus on when integrating multiple configurations:
- How to integrate multiple configuration information into a whole
- How to implement cross-configuration injection
- How to integrate multiple configuration information into a whole
- How to implement cross-configuration injection
- Additionally, annotations can be added directly to AppConfig via @Import
@Configuration @Import(AppConfig2.class) public class AppConfig1 { @Bean public UserDao userDao(){ return new UserDaoImpl(); } } //test @Test public void test4() { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig1.class); UserDaoImpl userDao = (UserDaoImpl) ctx.getBean("userDao"); UserServiceImpl userService = (UserServiceImpl) ctx.getBean("userService"); System.out.println(userDao); System.out.println(userService); }
- This @Import comment is identical to the <import resource ='>'tag in the XML file
The last way is to specify multiple lass objects to configure the Bean when the factory is created: (with less knowledge, you can)
- ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig1.class,AppConfig2.class);
- This approach works for all scenarios where a configuration Bean is applied (P194 doesn't understand it)
# Regardless of how configuration information is aggregated during the application of a configuration Bean, it is done by using member variables with the @AutoWired annotation2) Configuration Bean integration with @Component related notes
Configuration beans are DAO injected after integration:
Injection directly using @AutoWired
@Configuration @ComponentScan(basePackages="com.jun.injection") public class AppConfig3{ @Autowired //Make the content you need to inject a member variable private UserDAO userDAO; @Bean public UserService userService(){ UserServiceImpl userService = new UserServiceImpl(); userSercvice.setUserDAO(userDAO); return userService; } }3) Configuration Bean and Configuration File Integration
# Note that when configuring Bean injection, a red downwave warning may occur using @AutoWried because idea is a tool that is unexpected and normal.
5. Configuration Bean's underlying implementation
(p197 didn't understand)
# After Spring adds the @Configuration annotation to the configuration beans, the underlying layer configures and handles it via Cglib.
6. Development Thought of Four-in-One
- What is Four-Dimensional Integration
- Spring develops four forms of a function, and although they are developed in different ways, the end result is the same.
- schema-based
- Annotate @PropertySource based on specific functionality [Recommended]
- Based on the original <bean id="" class="PropertySourcePlaceholderConfigure"/>
- Based on the @Bean comment [Recommended]
7. Pure Annotation AOP Programming
- Set up environment
- Apply Configuration Bean
- Annotation Scan
Development steps
1. Original Object @Service public class UserServiceImpl implements UserService{} 2. Create a facet class (additional features, entry points, assembly facets) @Aspect @Component public class MyAspect { @Pointcut("execution(* com.jun.aop..*.*(..))") public void pointCut(){} @Around("pointCut()") // Additional features + entry point public Object around(ProceedingJoinPoint joinPoint) throws Throwable{ System.out.println("------aspectj log ----"); Object ret = joinPoint.proceed(); return ret; } } 3.Spring A special tag is configured in the configuration file: <aop:aspectj-autoproxy> and @EnableAspectjAutoProxy Equivalent (written in configuration) Bean In) @Configuration @ComponentScan(basePackages = "com.jun.aop") @EnableAspectJAutoProxy public class AppConfig { }
AOP Detail Analysis
@EnableAspectjAutoProxy1. Create proxy switch (There are two ways to create the underlying dynamic proxy: JDK CGlib) <aop:aspectj-autoproxy proxy-target-clsss = true|false> //True->cglib; False (default) ->jdk Based on pure annotations: @Configuration @ComponentScan(basePackages = "com.jun.aop") @EnableAspectjAutoProxy(proxyTargetClass = true) //Switch jdk proxy creation to cglib creation public class AppConfig{} 2.SpringBoot AOP Development methods @EnableAspectjAutoProxy Already set It only needs: 1.Create original object 2.Create a facet class (additional features, entry points, assembly facets) # The default implementation of the Spring AOP proxy is JDK, while the default implementation of the SpringBoot AOP proxy is Cglib
8. Pure Annotation Spring+MyBatis Integration
- Note: The return value in the public DruidDataSource dataSource() above is best defined as: public DataSource dataSource
@MapperScan
Pure annotation spring+mybatis integrated encoding
Wildcard Writing for MapperLocations Encoding
ResourcePatternResolver//Set the path to the Mapper file sqlSessionFactoryBean.setMapperLocations(Resource..); Resource resource = new ClassPathResource("UserDAOMapper.xml"); sqlSessionFactoryBean.setMapperLocations(new ClassPathResource("UserDAOMapper.xml")); <property name = "mapperLocations"> <list> <value> classpath:com.jun.mapper/*Mapper.xml</value> <list> </property> In Configuration Bean It can be written like this:(Put a group Mapper File passed to sqlSessionFactoryBean)[Standard Writing in Development) ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resolver.getResources("com.jun.mapper/*Mapper.xml"); sqlSessionFactoryBean.setMapperLocations(resources);
Resolve Configuration Bean Data Coupling
Then inject MybatisProperties into the configuration Bean.
9. Transaction programming in annotated version
- Annotation Controller Development (Annotation MVC Integration) is not yet complete
10. Use of YML in Spring Framework
-
YML(YAML) is a new form of configuration file that is simpler than XML and more powerful than properties.
-
There is a problem with the properties configuration file
- Properrties expression is too cumbersome to express the intrinsic relationship of data.
- Properrties cannot express object collection types.
- YML Syntax
1. Definition yml Files: xxx.yml,xxx.yaml 2. Grammar: 1. Basic grammar: name: jun password: 1324 2.Object concepts account: id: 1 password: 14324 3.Define Set(as List aggregate) service: - 1111 - 2222
Spring and YML file integration
# First Spring does not support YML files First is YamlPropertiesFactoryBean This factory that creates complex objects will YML File Creation properties File, and then give it to PropertySourcePlaceholderConfigurer Processing.
Spring and YML integrated encoding
- Environment Setup: Introduce the jar package of snakeyaml (because YamlPropertiesFactoryBean parses the yml accordingly) [Note that the minimum version is 1.18]
<dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.28</version> </dependency>
- Code
1.Get ready yml configuration file 2.To configure Bean Medium operation, complete YAML Read, and PropertySourcePlaceholderConfigurer Creation @Configuration @ComponentScan(basePackages = "com.jun.yml") public class YmlAutoConfiguration { @Bean public PropertySourcesPlaceholderConfigurer configurer(){ YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean(); yamlPropertiesFactoryBean.setResources(new ClassPathResource("init.yml")); Properties properties = yamlPropertiesFactoryBean.getObject(); PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); configurer.setProperties(properties); return configurer; } } 3.Add on a specific class@Value annotation @Component public class Account { @Value("$") private String name; @Value("$") private String password; set...... get...... } //test @Test public void test(){ ApplicationContext ctx = new AnnotationConfigApplicationContext(YmlAutoConfiguration.class); Account account = (Account) ctx.getBean("account"); System.out.println("account.getName() = " + account.getName()); System.out.println("account.getPassword() = " + account.getPassword()); } //If the yml configuration file is in the form of an object: @Value("$")Problems with Spring and YML integration
age = -11 -12 -13 Spring Of YamlPropertiesFactoryBean Still can't solve this problem # Solve using Spring's EL expression list: 11,12,13 @Value(#{$.split(',')}) private List<String> list; //Test: @Test public void test(){ ApplicationContext ctx = new AnnotationConfigApplicationContext(YmlAutoConfiguration.class); Account account = (Account) ctx.getBean("account"); List<String> list = accout.getList(); for(String s : list){ System.out.println("s = " + s); } } 2.Object type YAML When configuring,@Value("$")Too cumbersome # The @ConfigrationProperties provided by springBoot better solves this problem