本节内容
- 之前我们基于xml配置时使用的是ClassPathXmlApplicationContext这个ApplicationContext接口的实现类,本节我们要学习的是使用AnnotationConfigApplicationContext这个实现类进行ApplicationContext 容器的初始化操作,这在这个过程中我们将学习到
@Configuration、@ComponentScan、@Bean、@Import @PropertySource这几个新的注解。 - 我们要把上两节写的项目进行改写,改写成通过使用config.class文件进行spring配置的方式。
代码简单展示
package com.lujuan.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.lujuan")
public class SpringConfigration {
@Bean(name = "queryRunner")
public QueryRunner method1( @Qualifier(value = "dataSource")ComboPooledDataSource ds, @Qualifier(value = "dataSource")ComboPooledDataSource ds2){
System.out.println(ds==ds2);
return new QueryRunner(ds);
}
@Bean(name="dataSource")
public ComboPooledDataSource method2(){
ComboPooledDataSource ds = null;
try{
ds = new ComboPooledDataSource();
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy?characterEncoding=utf8");
ds.setUser("root");
ds.setPassword("Admin@123");
}catch (Exception e){
}
return ds;
}
}
package com.lujuan;
import com.lujuan.domain.Account;
import com.lujuan.service.impl.AccountServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = "classpath:bean.xml")
@ContextConfiguration(classes = com.lujuan.config.SpringConfigration.class)
public class AccountServiceTest {
@Autowired
private AccountServiceImpl ac;
@Test
public void testFindAll(){
List<Account> accounts = ac.findAllAccount();
for(Account account:accounts)
System.out.println(account.toString());
}
@Test
public void testFindAccountById() {
Account account = ac.findAccountById(1);
System.out.println(account);
}
@Test
public void testAddAccount() {
Account account = new Account();
account.setName("ddd");
account.setMoney(2000f);
ac.addAccount(account);
}
@Test
public void testDeleteAccountById() {
ac.deleteAccountById(1);
}
@Test
public void testUpdateAccount() {
Account account = ac.findAccountById(4);
account.setName("eeee");
account.setMoney(3333f);
ac.updateAccount(account);
}
}
执行我们的测试类中的方法,我们可以看到应用这种方法我们也能够正常的执行成功。我们主要是完成一个一个config类,然后在测试类中通过使用AnnotationConfigApplicationContext这个容器类进行容器和bean对象的初始化。
改写上一个工程项目
解释说明
- @Configuration:表明当前类是一个配置类,可用于ApplicationContext的初始化。
- @ComponentScan:用来扫描那些使用注解的进行配置的包
- @Bean :对于那些其他人的jar包中生成的bean对象,可用这种方式进行。
其他的注解可以用的时候再学习。



京公网安备 11010502036488号