学习视频:【孙哥说Spring5:从设计模式到基本应用到应用级底层分析,一次深入浅出的Spring全探索。学不会Spring?只因你未遇见孙哥】
Spring开发一个功能的4种形式,虽然开发方式不同,但是最终效果都是一样的。
1.<context:property-placeholder
2.@PropertySource **[推荐]**
3.<bean id="" class="PropertySourcePlaceholderConfigure"/>
4.@Bean [推荐]
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当中
代理创建方式的切换 JDK Cglib
回顾:
通过@EnableAspectjAutoProxy(proxyTargetClass)来切换
SpringBoot AOP的开发方式
实际上也是上面那三步,只不过最后一步不需要我们做了
Spring AOP 代理默认实现 JDK SpringBoot AOP 代理默认实现 Cglib
基础配置(配置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&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文件
//设置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);
将配置类中的字符串信息放到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;
}
}
回顾事务开发步骤
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
YML(YAML)是一种新的配置文件形式,比xml更简单,比Properties更强大。
如何定义yml文件
创建以yml结尾的文件即可 xxx.yml xxx.ymal
语法
基本语法
name: suns
password: 123456
对象概念
account:
id:1
password:123456
定义集合
service:
1111
2222
准备yml配置文件
init.yml
name: suns
password: 123456
读取yml 转换成 Properties
YamlPropertiesFactoryBean.setResources(yml配置文件的路径) new ClassPathResource();
YamlPropertiesFactoryBean.getObject() —→ Properties
应用PropertySourcePlaceholderConfigurer
PropertySourcePlaceholderConfigurer.setProperties();
类中 @Value注解 注入
环境搭建
org.yaml
snakeyaml
1.23
编码
准备yml配置文件
配置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;
}
在特定类加入 @Value注解
集合解析失败处理的问题
SpringEL表达式解决
@Value("#{'${list}'.split(',')}")
private List<String> list;
对象类型的YAML进行配置时 过于繁琐
@Value(”${account.name}”)
后续的SpringBoot可以解决上面的两个问题 @ConfigurationProperties