Spring 实现CRUD

1. 基于xml

文件结构:

2. 基于注释

改进:是否可以去掉bean.xml文件以及测试@test中减少重复代码

3. 将bean.xml替换为配置类文件

改进:将单例对象创建方式改为多例

4.如果有多个配置类,则需注明每个要扫描的包,并在每个类的头部注明@Configuration:

@Configuration
@ComponentScan({"com.alan","config"})
public class SpringConfiguration {

}
package config;
@Configuration
public class JdbcConfig {}

或者在AnnotationConfigApplicationContext()创建时传入多个配置类参数,但这样体现不了配置类的主次关系,配置类有时候分为主配置文件和很多子配置文件

ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class,JdbcConfig.class);

第三个方法是在主配置文件中使用@Import导入其他类的字节码

 /**  Import
 *      用于导入其他类,值为其他类的字节码
@ComponentScan("com.alan")
@Import(JdbcConfig.class)
public class SpringConfiguration {

}

5. 把数据库连接所需参数也写在配置文件中

jdbcConfig.properties

driverClass=com.mysql.jdbc.Driver
Url=jdbc:mysql://localhost:3306/db03
User=root
Password=xiaoyahuan1997

 子配置文件JdbcConfig.java

public class JdbcConfig {
    @Value("${driverClass}")
    private String driver;
    @Value("${Url}")
    private String url;
    @Value("${User}")
    private String user;
    @Value("${Password}")
    private String pwd;
}

主配置文件SpringConfiguration.java

需表明数据配置文件的路径 

 /**  PropertiesSource
 *      用于指定properties文件的位置
 *      属性:
 *          value,指定文件的名称和路径,关键字:classpath表示类路径
 */
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {

}

6. 如果存在多个数据源,会根据参数名和bean的id是否一致来进行匹配

也可以在参数前加上@Qualifier("beanId")来指定数据源

    /**
    * 参数前加@Qualifier("ds1")
    */
    @Bean(name="runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(@Qualifier("ds1") DataSource dataSource) {
        return new QueryRunner(dataSource);
    }

    @Bean(name="ds1")
    @Scope("prototype")
    public DataSource createDataSource() {
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(user);
            ds.setPassword(pwd);
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Bean(name="ds2")
    @Scope("prototype")
    public DataSource createDataSource1() {
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/db02");
            ds.setUser(user);
            ds.setPassword(pwd);
            return ds;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

7. Spring 整合junit

7.1 junit集成了一个main方法,该方法会判断当前测试类中哪些方法有@Test注解

7.2 junit不关心是否使用了spring框架,所以也不会读取配置文件/配置类创建spring核心容器

7.3 两种方法:

    private ApplicationContext ac;
    private IAccountService as;
    //在测试单元外声明,并在@Before中赋值
    @Before
    public void init() {
        ac = new AnnotationConfigApplicationContext();
        as = ac.getBean("acountService", IAccountService.class);
    }
    @Test
    public void testFindAll() {
        //执行方法
        List<Account> accounts = as.findAllAccount();
        for(Account acc : accounts)  {
            System.out.println(acc);
        }
    }

第二种:使用Spring中的

 /** 1.导入spring整合junit的jar
 *   2.使用junit提供的注解把原有的main方法替换成spring提供的@Runwith
 *   3.告知spring的运行器,spring和ioc创建是基于xml还是注解的,并说明位置
 *   @ContextConfiguration
 *      locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
 *      classes:指定注解类所在的位置
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=SpringConfiguration.class)
public class AccountServiceTest {
    @Autowired
    //因为不用xml或者注释所以不用声明AnnotationConfigApplicationContext()
    private IAccountService as = null;
    @Test
    public void testFindOne() {
        //执行方法
        Account account = as.findAccountById(4);
        System.out.println(account);
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值