Spring-全注解开发

导入需要使用的命名空间

<?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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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
      http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
          http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
">
</beans>

声明注解开发

<!--  context:component-scan扫描特定的包  -->
<context:component-scan base-package="my"></context:component-scan>
<!--    表示使用注解-->
<context:annotation-config></context:annotation-config>
<!--    开启注解事务处理-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>


自定义的配置类

@Configuration//声明为配置类
@ComponentScan("my")//扫描的包
@EnableTransactionManagement//开启事务
public class MyConfig {
    @Bean
   public DataSource getDataSource(){

       DruidDataSource dataSource=new DruidDataSource();
       dataSource.setUrl("jdbc:mysql://localhost:3306/test?serverTimezone=UTC");
       dataSource.setUsername("root");
       dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
       dataSource.setPassword("1602820115");
       return dataSource;
   }
   @Bean
   public JdbcTemplate getJdbcTemplate(DataSource dataSource){
       JdbcTemplate jdbcTemplate = new JdbcTemplate();
       jdbcTemplate.setDataSource(dataSource);
       return jdbcTemplate;
   }
//   public CustomerDao getCustomerDao(JdbcTemplate jdbcTemplate){
//       CustomerDaoImpl customerDao = new CustomerDaoImpl();
//       customerDao.setJdbcTemplate(jdbcTemplate);
//       return customerDao;
//   }
//   @Bean
//   public CustomerService getCustomerService(CustomerDao customerDao){
//       CustomerServiceImpl customerService = new CustomerServiceImpl();
//       customerService.setCustomerDao(customerDao);
//       return customerService;
//   }
    //创建事务管理器
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}

需要 注意的是,bean方法的名字就是返回对象的id

上一篇:Dubbo源码剖析五之服务本地缓存


下一篇:Dubbo-go 优雅上下线设计与实践