spring框架-将XML文件配置转为配用置类实现

spring框架-将XML文件转为配用置类实现

需要待转为配置类的xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

   <context:component-scan base-package="cn.edu.cafuc"></context:component-scan>

   <bean id="runner" class="org.apache.commons.dbutils.QueryRunner">
      <!--注入数据源-->
       <constructor-arg name="ds" ref="dataSource"></constructor-arg>
   </bean>
   <!--配置数据源-->
   <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
       <!--连接数据的信息-->
       <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
       <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/user?useUnicode=true&amp;characterEncoding=gbk&amp;useJDBCCompliantTimezoneShift=true&amp;serverTimezone=UTC"></property>
       <property name="user" value="root"></property>
       <property name="password" value="123456"></property>
   </bean>
</beans>

详细步骤

首先创建一个配置类,该类的作用与xml配置文件作用一样

  • @Configuration:指定当前类是一个配置类
    细节:当配置类作为AnnotationConfigApplicationContext对象的创建参数时,@Configuration可以不写
 @Configuration
public class SpringConfiguration {
/**
 *用于配置公共的配置
 */
}

对于如下xml配置

<context:component-scan base-package="cn.edu.cafuc"></context:component-scan>

spring提供了一个注解

  • @ComponentScan:用于指定spring容器要扫描的包
    属性:value,basePackages
@Configuration
@ComponentScan(value = "cn.edu.cafuc")
public class SpringConfiguration {
/**
*用于配置公共的配置
*/
}

对于如下xml配置

<bean id="runner" class="org.apache.commons.dbutils.QueryRunner">
	<!--注入数据源-->
 	<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!--配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <!--连接数据的信息-->
    <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/user?useUnicode=true&amp;characterEncoding=gbk&amp;useJDBCCompliantTimezoneShift=true&amp;serverTimezone=UTC"></property>
    <property name="user" value="root"></property>
    <property name="password" value="123456"></property>
</bean>

我们可以在配置类中创建两个方法分别返回两个对象,对于数据库操作QueryRunner对象为了线程安全,采用注解Scope指定多例

  • @Bean:用于把当前方法返回值作为bean对象存入spring容器IOC
    属性:
    name:用于指定bean的id。当不写时值为当前方法的名称
    细节: 当我们使用注解配置时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象
    查找方式和Autowried注解作用一样,例如下的createQueryRunner的方法参数dataSource。
/**
 * 用于创建Queryrunner对象
 *
 * @param dataSource
 * @return
 */
@Bean(name = "runner")
@Scope("prototype")
public QueryRunner createQueryRunner(DataSource dataSource) {
    return new QueryRunner(dataSource);
}

/**
 * 创建数据源对象
 * @return
 */
@Bean(name = "dataSource")
public DataSource createDataSource() {
    ComboPooledDataSource ds = new ComboPooledDataSource();
    try {
        ds.setDriverClass(driver);
        ds.setJdbcUrl(url);
        ds.setUser(username);
        ds.setPassword(password);
        return ds;
    } catch (PropertyVetoException e) {
        throw new RuntimeException(e);
    }
}

spring给我们提供了另一个注解

  • @import
    作用用于导入其他配置类
    属性:value: 用于指定其他配置类字节码
    使用Import注解之后的类为父配置类,导入的类为子配置类
@Import(JdbcConfiguration.class)
public class SpringConfiguration {
/**
 *用于配置公共的配置
 */
}
  • @PropertySource
    作用:用于指定properties文件位置
    属性: value:指定文件名称和路径
    关键字:classpath:类路径
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
/**
 *用于配置公共的配置
 */
}

最后将上面的xml配置文件转换为配置类实现,如下:

@Configuration
@ComponentScan(value = "cn.edu.cafuc")
@Import(JdbcConfiguration.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
/**
 *用于配置公共的配置
 */
}
//@Configuration
public class JdbcConfiguration {
    @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对象
     *
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource) {
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource createDataSource() {
        ComboPooledDataSource ds = new ComboPooledDataSource();
        try {
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }
    }
}

最后调用处获得容器代码如下:

ApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfiguration.class);
IAccountService as = ac.getBean("accountService", IAccountService.class);

特别注意:本文章是学习Spring视频教程 -IEDA版-4天-2018黑马SSM 所记录知识总结

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值