spring的xml以及纯注解综合案例

一、Spring的XML的环境搭建案例实现数据库CRUD

     1.Spring基础知识:springIOC的基础https://www.cnblogs.com/cqyp/p/12497509.html

                                    依赖注入:https://www.cnblogs.com/cqyp/p/12498972.html

     2.Bean.xml的配置          

 <!--配置Service-->
    <bean id="accountService" class="com.li.service.impl.AccountServiceImpl">
        <!--注入dao对象,在类中要实现accountDao的set的方法-->
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    <!--配置dao-->
    <bean id="accountDao" class="com.li.dao.impl.AccountDaoImpl">
        <!--注入QueryRunner对象-->
        <property name="runner" ref="runner"></property>
    </bean>
    <!--配置QueryRunner对象-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入数据源-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>
    <!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--连接数据库的必备信息-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///spring"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123"></property>
    </bean>

    3.环境搭建的最终源码https://github.com/Cqypyglz/spring/tree/602f4c4487b2ac578e7e4ba26fb35ef644f476d3

                             

 

二、注解的环境搭建案例实现数据库CRUD

       1.创建一个配置类,作用与Bean.xml(spring 的配置文件)的作用一致;

            spring的新注解:

                   @Configuration:  指定当前类为配置类(即创建Bean.xml文件)

                   @ComponentScan:  用于通过注解指定spring在创建容器时要扫描的包

                           属性:

                              value:它和basePackages的作用一样,都是用于创建容器时所扫描的包

                              此注解就等同于xml的配置:<context:component-scan base-package="com.li"></context:component-scan>

                   @Bean: 用于把当前的返回值作为bean对存入spring的IOC容器中

                              属性:name:指定bean的id,如果不指定,为当前方法的名称;

                               细节:当我们使用注解配置方法时,如果方法有参数,spring框架回去容器中查找有没有可用的bean对象,查找的方法和Autowired注解的作用一样的,自动按照类型注入

                   @Import: 导入其他类

                          属性:value:用于指定其他配置类的字节码 

                          当我们使用Import的注解后,有Import注解的类就是父配置类,而导入的为子配置类;

                   @propertySource: 用于指定properties文件位置

                           属性 classpath:用于指定文件名名称和路径

            

//配置类
@Configuration @ComponentScan(
"com.li") @Import(JdbcConfig.class) @PropertySource("classpath:jdbcConfig.properties") public class SpringConfiguration { }

/**
 * 和spring连接数据库相关的配置类
 */
public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    /**
     * 用于创建一个QueryRunner对象,封装jdbc连接数据库,
     */
    @Bean("runner")
    @Scope("prototype")
    public QueryRunner creatQueryRunner(@Qualifier("ds1") DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean("ds1")
    public DataSource dataSource(){
        try {
            ComboPooledDataSource ds =new ComboPooledDataSource(); //使用连接池创建数据源
            ds.setDriverClass(driver); //加载驱动
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }
    }
    @Bean(name="ds2")
    public DataSource dataSource2(){
        try {
            ComboPooledDataSource ds =new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl("jdbc:mysql:///mbase");
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }
    }
}

 

 

     2.测试类中Spring整合Junit的配置

           1)导入Spring整合Junit的jar坐标

           2)使用junit提供的注解把原有main方法替换,替换成spring提供的;

           3)告知spring运行器,spring和ioc创建时基于xml还是注解,并说明位置;

                @ContextConfiguration:

                      属性:locations:指定xml位置,加上classpath关键字,表示在类路劲下

                                      @ContextConfiguration(locations = "classpath:bean.xml")

                                classes:指定注解类的位置:

                                      @ContextConfiguration(classes = SpringConfiguration.class)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
    @Autowired
private IAccountService as=null;
    @Test
    public void testFindAll(){
        //3.执行方法
        List<Account> accounts = as.findAllAccount();
        for (Account account:accounts){
            System.out.println(account);
        }
    }

 

         3.环境搭建的最终源码https://github.com/Cqypyglz/spring/tree/602f4c4487b2ac578e7e4ba26fb35ef644f476d3           

          

posted @ 2020-03-16 17:55  撑起一片阳光  阅读(357)  评论(0编辑  收藏  举报