Spring全注解开发
2020-02-03 本文已影响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));
}