Spring5学习随笔-纯注解开发、YML详解

发布时间 2023-11-24 20:30:56作者: 扬眉剑出鞘

学习视频:【孙哥说Spring5:从设计模式到基本应用到应用级底层分析,一次深入浅出的Spring全探索。学不会Spring?只因你未遇见孙哥】

7.四维一体的开发思想

1.什么是四维一体

Spring开发一个功能的4种形式,虽然开发方式不同,但是最终效果都是一样的。

  1. 基于schema
  2. 基于特定功能注解
  3. 基于原始<bean
  4. 基于@Bean注解

2.四维一体的开发案例

1.<context:property-placeholder
2.@PropertySource **[推荐]**
3.<bean id="" class="PropertySourcePlaceholderConfigure"/>
4.@Bean [推荐]

8.纯注解版AOP编程

1.搭建环境

  1. 应用配置Bean
  2. 注解扫描

2.开发步骤

1. 原始对象
    @Service(@Component)
    public class UserServiceImpl implements UseService{
		    
    }
2. 创建切面类(额外功能 切入点 组装切面)
		@Aspectj
		@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的配置文件中
    <aop:aspectj-autoproxy/>
    @EnableAspectjAutoProxy 放在配置Bean当中

3.注解AOP细节分析

  1. 代理创建方式的切换 JDK Cglib

    回顾:<aop:aspectj-autoproxy proxy-target-class=true|false/>

    通过@EnableAspectjAutoProxy(proxyTargetClass)来切换

  2. SpringBoot AOP的开发方式

    实际上也是上面那三步,只不过最后一步不需要我们做了

  3. Spring AOP 代理默认实现 JDK SpringBoot AOP 代理默认实现 Cglib

9.纯注解版Spring+MyBatis整合

  • 基础配置(配置Bean)

    1、连接池
    		<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/suns?useSSL=false&amp;allowPublicKeyRetrieval=true"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
        </bean>
    
    		@Bean  //代替上面的xml配置
    		public DruidDataSource dataSource(){
    				DruidDataSource dataSource = new DruidDataSource();
    				dataSource.setDriverClassName("");
    				dataSource.setUrl();
    				....
    				return dataSource;
    		}
    2、SqlSessionFactoryBean
    		<!-- 创建SqlSessionFactory SqlSessionFactoryBean-->
        <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="typeAliasesPackage" value="com.baizhi.entity"/>
            <property name="mapperLocations">
                <list>
                    <value>classpath:com.baizhi.mapper/✳Mapper.xml</value>
                </list>
            </property>
        </bean>
    
    		@Bean //代理上面的xml配置
    		public SqlSessionFactoryBean sqlSessionFactoryBean(){
    				SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    				sqlSessionFactoryBean.sqlDataSource(dataSource);
    				.....
    				return sqlSessionFactoryBean;
    		}
    3、MapperScannerConfigure
    		<!--创建DAO对象 MapperScannerConfigure-->
        <bean id="scanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/>
            <property name="basePackage" value="com.baizhi.dao"/>
        </bean>
    			
    		@MapperScan(basePackages="com.baizhi.dao")
    
  • 编码

    1、实体
    2、表
    3、DAO接口
    4、Mapper文件
    

1.MapperLocation编码时通配的写法

//设置Mapper文件的路径
sqlSessionFactoryBean.setMapperLocations(new ClasPathResource("UserDaoMapper.xml");//只能获取一个Mapper文件

回顾之前的通配形式获取一组Mapper文件
		<property name="mapperLocations">
        <list>
            <value>classpath:com.baizhi.mapper*Mapper.xml</value>
        </list>
    </property>

//使用spring为我们提供的类,可以基于通配的形式为我们解析一组Mapper文件了@Value("${mybatis.driverClassName}")@
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources(mybatisProperties.getMapperLocations());
sqlSessionFactoryBean.setMapperLocations(resources);

2.配置Bean数据耦合的问题

将配置类中的字符串信息放到properties配置文件中,用一个类封装其信息,在配置类中用@Autowired注入,填入封装信息
1. properties文件
mybatis.driverClassName = com.mysql.jdbc.Driver
mybatis.url = jdbc:mysql://localhost:3306/suns?useSSL=false
mybatis.username = root
mybatis.password = 123456
mybatis.typeAliasesPackage = com.baizhi.mybatis
mybatis.mapperLocations = com.baizhi.mapper/✳Mapper.xml

2.进行封装
@Component
@PropertySource("classpath:mybatis.properties")
public class MybatisProperties {
    @Value("${mybatis.driverClassName}")
    private String driverClassName;
    @Value("${mybatis.url}")
    private String url;
    @Value("${mybatis.username}")
    private String username;
    @Value("${mybatis.password}")
    private String password;
    @Value("${mybatis.typeAliasesPackage}")
    private String typeAliasesPackage;
    @Value("${mybatis.mapperLocations}")
    private String mapperLocations;

3.配置Bean
@Configuration
@ComponentScan(basePackages = "com.baizhi.mybatis")
@MapperScan(basePackages = "com.baizhi.mybatis")
public class MyBatisAutoConfiguration {

    @Autowired
    private MybatisProperties mybatisProperties;

    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(mybatisProperties.getDriverClassName());
        dataSource.setUrl(mybatisProperties.getUrl());
        dataSource.setUsername(mybatisProperties.getUsername());
        dataSource.setPassword(mybatisProperties.getPassword());
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage(mybatisProperties.getTypeAliasesPackage());
//        sqlSessionFactoryBean.setMapperLocations(new ClassPathResource("UserDAOMapper.xml"));
        try {
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources(mybatisProperties.getMapperLocations());
            sqlSessionFactoryBean.setMapperLocations(resources);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSessionFactoryBean;
    }
}

10.纯注解版事务编程

回顾事务开发步骤

1.原始对象 XXXService
	<bean id="userService" class="com.baizhi.service.UserServiceImpl">
      <property name="userDao" ref="userDao"/>
  </bean>

	@Service 代替xml配置文件
	public classUserServiceImpl implements UserService{
			@Autowired
			privarte UserDao userDao;
	}
2.额外功能
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

@Bean
public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource){
		DataSourceTransactionManager dstm = new DataSourceTransactionManager();
		dstm.setDataSource(dataSource);
		return dstm;
}
3.事务属性
@Transactional(rollbackFor = {Exception.class},noRollbackFor = {RuntimeException.class})
@Service
public class UserServiceImpl implements UserService {
		@Autowired    
		private UserDao userDao;

4.基于Schema的事务配置
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
@EnableTransactionManager --->配置Bean

11.Spring框架中YML的使用

1.什么是YML

YML(YAML)是一种新的配置文件形式,比xml更简单,比Properties更强大。

2.Properties进行配置的问题

  1. Properties表达过于繁琐,无法表达数据的内在联系。
  2. Properties无法表达对象、集合类型。

3.YML语法简介

  1. 如何定义yml文件

    创建以yml结尾的文件即可 xxx.yml xxx.ymal

  2. 语法

    1. 基本语法

      name: suns

      password: 123456

    2. 对象概念

      account:

      id:1

      password:123456

    3. 定义集合

      service:

      • 1111

      • 2222

4.Spring与YML整合思路

  1. 准备yml配置文件

    init.yml

    name: suns

    password: 123456

  2. 读取yml 转换成 Properties

    YamlPropertiesFactoryBean.setResources(yml配置文件的路径) new ClassPathResource();

    YamlPropertiesFactoryBean.getObject() —→ Properties

  3. 应用PropertySourcePlaceholderConfigurer

    PropertySourcePlaceholderConfigurer.setProperties();

  4. 类中 @Value注解 注入

5.Spring与YML集成编码

  • 环境搭建

    <dependency>
        <groupId>org.yaml</groupId>
        <artifactId>snakeyaml</artifactId>
        <version>1.23</version>
    </dependency>
    
  • 编码

    1. 准备yml配置文件

    2. 配置Bean中操作 完成YAML读取 与PropertySourcePlaceholderConfigure的创建

      @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. 在特定类加入 @Value注解

6.Spring与YML集成的问题

  1. 集合解析失败处理的问题

    SpringEL表达式解决

    @Value("#{'${list}'.split(',')}")
    private List<String> list;
    
  2. 对象类型的YAML进行配置时 过于繁琐

    @Value(”${account.name}”)

后续的SpringBoot可以解决上面的两个问题 @ConfigurationProperties