1.引入依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
</dependencies>
2.resources下编写properties文件,用于连接数据库
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false
jdbc.username=root
jdbc.password=root
3.使用注解@PropertySource引入数据库配置文件,使用注解@Bean创建DruidDataSource
@PropertySource("classpath:jdbc.properties")
public class JDBCConfig {
@Value("${jdbc.driver}")
private String Driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean("dataSource")
public DruidDataSource getDataSource(){
DruidDataSource ds=new DruidDataSource();
ds.setDriverClassName(Driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
4.使用注解@Bean创建SqlSessionFactoryBean 和MapperScannerConfigurer ,分别用来配置数据源和扫描实体类bean以及mapper映射文件
public class MyBatisConfig {
@Bean
public SqlSessionFactoryBean getSqlSessionFactoryBean(@Autowired DataSource dataSource){
SqlSessionFactoryBean sessionFactoryBean=new SqlSessionFactoryBean();
sessionFactoryBean.setTypeAliasesPackage("com.zfz.bean");
sessionFactoryBean.setDataSource(dataSource);
return sessionFactoryBean;
}
@Bean
public MapperScannerConfigurer getMapperScannerConfigurer(){
MapperScannerConfigurer msc=new MapperScannerConfigurer();
msc.setBasePackage("com.zfz.mapper");
return msc;
}
}
5.使用以下注解引入上述两个配置,并指明spring扫描基础包
@Configuration
@ComponentScan("com.zfz")
@Import({JDBCConfig.class,MyBatisConfig.class})
public class SpringConfig {
}
6.写dao层接口
public interface AccountMapper {
@Insert(" insert into account(name, money)\n" +
" values (#{name}, #{money})")
void save(Account account);
@Delete(" delete\n" +
" from account\n" +
" where id = #{id}")
void delete(Integer id);
@Update(" update account\n" +
" set name=#{name},\n" +
" money=#{money}\n" +
" where id = #{id}")
void update(Account account);
@Select(" select *\n" +
" from account")
List<Account> findAll();
@Select(" select *\n" +
" from account\n" +
" where id = #{id}")
Account findById(Integer id);
}
7.service层接口
public interface AccountService {
void save(Account account);
void delete(Integer id);
void update(Account account);
List<Account> findAll();
Account findById(Integer id);
}
8.service实现及注入dao
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountMapper accountDao;
@Override
public void save(Account account) {
accountDao.save(account);
}
@Override
public void delete(Integer id) {
accountDao.delete(id);
}
@Override
public void update(Account account) {
accountDao.update(account);
}
@Override
public List<Account> findAll() {
return accountDao.findAll();
}
@Override
public Account findById(Integer id) {
return accountDao.findById(id);
}
}
9.测试
public class AccountApp {
public static void main(String[] args) {
ApplicationContext ctx=new AnnotationConfigApplicationContext(SpringConfig.class);
AccountService accountService = (AccountService) ctx.getBean("accountService");
List<Account> all = accountService.findAll();
for (Account account : all) {
System.out.println(account);
}
DruidDataSource dataSource = (DruidDataSource) ctx.getBean("dataSource");
System.out.println(dataSource);
}
}
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {SpringConfig.class})
public class AccountServiceTest {
@Autowired
private AccountService accountService;
@Test
public void findById(){
Account byId = accountService.findById(1);
Assert.assertEquals("Mike",byId.getName());
}
}
在测试中排除非自己写的bean,只需要能够加载启动自己方法的bean,其他的排除;比如我只测试dao层或者service层接口,但是我不需要让他们整个都跑,只需要排除即可
应用场景:当bean很多很多时,需要自己写导入器加载bean
自定义导入器
问题又来了:其中一个bean加载需要干很多事情,这个时候FcatoryBean来了
1.导入依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
2.把共性功能抽离出来,写到一个类中
这里是接口实现的一句话抽取
@Override
public void save() {
// System.out.println("共性功能");
System.out.println("userService running");
}
3. 写抽取的代码,制作通知类,在类中定义一个方法用于完成共性功能
public class AopAdvice {
public void function(){
System.out.println("共性功能");
}
}
4.这时候spring还不知道这之间的关系,现在做配置,将上面抽离出的共性功能类配置成一个bean,然后开启aop的命名空间支持,然后配置AOP
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启命名空间-->
<bean id="userService" class="com.zfz.service.impl.UserServiceImpl">
</bean>
<!-- 配置通知bean-->
<bean id="myAdvice" class="com.zfz.aop.AopAdvice"></bean>
<!--配置aop-->
<aop:config>
<!-- 配置切入点-->
<aop:pointcut id="pt" expression="execution(* *..*(..))"/>
<!-- 配置切面(切入点与通知的关系)-->
<aop:aspect ref="myAdvice">
<aop:before method="function" pointcut-ref="pt"></aop:before>
</aop:aspect>
</aop:config>
</beans>
1.@EnableAspectJAutoProxy 开启注解配置
@Configuration
@ComponentScan("com.zfz")
@EnableAspectJAutoProxy
public class SpringConfig {
}
2.切面类配置
@Component
@Aspect
public class AopAdvice {
@Pointcut("execution(* *(..))")
public void pt(){
}
@Before("pt()")
public void before(){
System.out.println("共性功能");
}
}
@Component("userService")
public class UserServiceImpl implements UserService {
@Override
public void save() {
// System.out.println("共性功能");
System.out.println("水泥墙");
}
}
public class decorator implements UserService{
private UserService userService;
public decorator(UserService userService){
this.userService=userService;
}
@Override
public void save() {
userService.save();
System.out.println("刮大白");
}
}
public class UserServiceProxy {
public static UserService getServiceProxy( UserService userService){
UserService service = (UserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(),
new Class[]{UserService.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object invoke = method.invoke(userService, args);
System.out.println("刮大白22");
System.out.println("贴壁纸22");
return invoke;
}
});
return service;
}
}
public class App {
public static void main(String[] args) {
UserService userService=new UserServiceImpl();
UserService userService1=UserServiceProxy.getServiceProxy(userService);
userService1.save();
}
}
业务层实现:主要是转钱的接口实现,要么都成功要么都失败
public void transfer(String outName, String inName, Double money) {
PlatformTransactionManager ptm = new DataSourceTransactionManager(dataSource);
TransactionDefinition td = new DefaultTransactionDefinition();
TransactionStatus ts = ptm.getTransaction(td);
accountMapper.inMoney(outName, money);
int i = 1 / 0;
accountMapper.outMoney(inName, money);
//提交事务
ptm.commit(ts);
}
@Configuration
@ComponentScan("com.zfz")
@EnableAspectJAutoProxy
@Import({JDBCConfig.class,MybatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}
@PropertySource("classpath:jdbc.properties")
public class JDBCConfig {
@Value("${jdbc.driver}")
private String Driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean("dataSource")
public DruidDataSource getDataSource(){
DruidDataSource ds=new DruidDataSource();
ds.setDriverClassName(Driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
@Bean
public PlatformTransactionManager platformTransactionManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}
@Transactional(propagation = Propagation.SUPPORTS,readOnly = false,isolation = Isolation.DEFAULT)
public interface AccountService {
@Transactional
void transfer(String outName,String inName,Double money);
}
Required:有事务就加入,没有事务自己新建一个
Requires_new 有没有事务我都新建
Supports:有事务就加入 没有就没有
Not_Supported 有没有事务都不管你 属于不支持状态
Mandatory:有事务就加入,没有事务 就报错 ;这个必须有事务才行
never:要求不带事务,如果有事务就报错,没事务刚好