美文网首页
Spring全注解开发

Spring全注解开发

作者: 走在冷风中吧 | 来源:发表于2020-02-03 14:58 被阅读0次
      package com.lily.config;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.*;
    
    import javax.sql.DataSource;
    
    @Configuration   //声明是配置文件
    @ComponentScan({"com.lily.dao","com.lily.service"})  //声明包扫描
    @PropertySource("classpath:druid_datasource_config.properties")  //声明配置文件
    public class Config {
    
        @Value("${jdbc.name}")  //配置文件的取值
        private String username;
        @Value("${jdbc.password}")
        private String password;
        @Value("${jdbc.url}")
        private String url;
        @Value("${jdbc.driver}")
        private String driver;
    
        @Bean  //声明提供类
        public DataSource getDataSource(){
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setUsername(username);
            druidDataSource.setPassword(password);
            druidDataSource.setDriverClassName(driver);
            druidDataSource.setUrl(url);
            return druidDataSource;
        }
    
    }
    
    

    Dao

    @Component  //声明类对象
    public class AccountDaoImpl implements AccountDao {
    
    
        @Autowired  //获取类对象
        private DataSource dataSource;
    
        @Override
        public List<AccountBean> queryAll() {
            QueryRunner queryRunner = new QueryRunner(dataSource);
            String sql = "select * from account";
            try {
                return queryRunner.query(sql, new BeanListHandler<AccountBean>(AccountBean.class));
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
    
    
        }
    }
    

    Service

    @Component("accountService")
    public class AccountServiceImpl implements AccountService {
    
        @Resource
        private AccountDao accountDao;
    
    
        @Override
        public void addAccount(AccountBean accountBean) {
            accountDao.addAccount(accountBean);
        }
    
        @Override
        public List<AccountBean> findAll() {
            return accountDao.queryAll();
        }
    }
    

    Test 测试:

        @Test
        public void test01(){
            ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
            AccountService bean = context.getBean(AccountService.class);
            List<AccountBean> all = bean.findAll();
            all.forEach(accountBean -> System.out.println(accountBean));
        }
    

    相关文章

      网友评论

          本文标题:Spring全注解开发

          本文链接:https://www.haomeiwen.com/subject/lephxhtx.html