spring IOC注解替换xml及spring和Junit整合

11 篇文章 0 订阅

spring 注解替换xml

主配置类

//@Configuration
//指定当前类为配置类
//配置类为AnnotationConfigApplicationContext的参数时,可以省略
@ComponentScan(basePackages = {"com.cc"})
//容器创建时要扫描的包 basePackages和value作用相同
@Import(JDBCConfig.class)
//引入其他配置类
@PropertySource("classpath:jdbcconfig.properties")
//@PropertySource("classpath:spring/config/JDBCConfig.properties") 在包里
//指定properties文件位置    多个用PropertySources
public class SpringConfiguration {
}

副配置类

public class JDBCConfig {

    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.user}")
    private String user;
    @Value("${jdbc.password}")
    private String password;

    /**
     * 创建queryrunner对象
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    //把当前方法的返回值作为bean对象存入容器
    //name  bean指定bean的id  默认为方法名
    @Scope("prototype")
    //指定为多例对象
    public QueryRunner createQueryRunner(@Qualifier("dataSource") DataSource dataSource){
        //Qualifier    匹配bean的id
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource createDataSource() {
        ComboPooledDataSource ds = new ComboPooledDataSource();
        ds.setJdbcUrl(url);
        ds.setUser(user);
        ds.setPassword(password);
        return ds;
    }
}

spring 整合Junit

@RunWith(SpringJUnit4ClassRunner.class)
//将Junit原有运行方法替换为spring的
@ContextConfiguration(classes = SpringConfiguration.class)
//spring ioc创建是基于注解还是xml的,并说明位置
//locations ="calsspath:bean.xml"  xml文件位置
public class AccountServiceTest {

    @Autowired
    IAccountService as;
    @Test
    public void testFindAll(){
        List<Account> accounts = as.findAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值