本篇是按照上一篇基于xml的代码来改的
此时已经可以把bean.xml删掉了
先来改造AccountServiceImpl和AccountDaoImpl实现类中的代码:
首先AccountDaoImpl和AccountServiceImpl实现类中的set都可以删掉了
然后在声明的变量上面增加Autowired用于自动注入
//AccountDaoImpl中
@Autowired
public QueryRunner runner;
//AccountServiceImpl中
@Autowired
private IAccountDao accountDao;
在实现类上表明注解用于创建bean对象
//AccountServiceImpl中
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
public List<Account> FindAll(){
return accountDao.FindAll();
}
}
//AccountDaoImpl中
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
public QueryRunner runner;
public List<Account> FindAll() {
try{
return runner.query("select * from account", new BeanListHandler<Account>(Account.class));
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
然后在创建一个配置类(SpringConfig):
创建一个子配置类(jdbcConfig):
(声明一下他们的作用,SpringConfig是用于整个项目的,即它包含项目中所有的配置类及负责一些总体相关的代码;而jdbcConfig是用于配置数据库)
//jdbcConfig
public class jdbcConfig {
@Value("${jdbc.driver}")
public String driver;
@Value("${jdbc.url}")
public String url;
@Value("${jdbc.username}")
public String username;
@Value("${jdbc.password}")
public String password;
@Bean("runner")
@Scope("prototype")
public QueryRunner creatQueryRunner(javax.sql.DataSource dataSource){
return new QueryRunner((javax.sql.DataSource)dataSource);
}
@Bean("dataSource")
public ComboPooledDataSource creatDataSource(){
try{
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
//SpringConfig
@ComponentScan("goulizi")
@Import(jdbcConfig.class)
@PropertySource("classpath:Config.Properties")
public class SpringConfig {
}
注意:此时我在jdbcConfig配置类中并没有将数据库连接的driver、url、username、password给具体写出来,而我为了不让他有种定死的感觉,我将它放在了一个properties文件中,这样需要求改的时候就直接在这里面修改了。 在SpringConfig中我使用了PropertySource这个注解用于指定那个properties文件的位置。
在resources中创建一个properties文件:
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/test
jdbc.username = root
jdbc.password = 1234
注意在jdbcConfig中用Value注解赋值时,spring的el语句必须与这个地方的名称相同。
修改Test测试类:
这里有两种方式:
一种是用junit自带的继承的main方法,这个方法无法加载spring容器,所以需要我们来给他加载。
@Test
public void TestFindAll(){
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
IAccountService as = ac.getBean("accountService", IAccountService.class);
List<Account> accounts = as.FindAll();
for (Account account : accounts){
System.out.println(account);
}
}
另一种是替换掉这个自带的main方法,给他换成一个可以加载spring容器的main方法
首先导入spring整合的junit的jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
接下来用Runwith注解将main方法换成spring的,并用ContextConfiguration来确定用的是xml还是注解类,并用它标明配置类所在的路径
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
注意:当使用spring5及以上版本时,junit的jar包所添加的依赖必须是4.12版本以上的。
程序运行:
