zoukankan      html  css  js  c++  java
  • spring的纯注解的IOC配置

    package config;

    import com.mchange.v2.c3p0.ComboPooledDataSource;
    import org.apache.commons.dbutils.QueryRunner;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.*;

    import javax.sql.DataSource;

    /**
    * 该类是一个配置类,它的作用和bean.xml一样
    * spring中的新注解
    * Configuration
    * 作用:指定当前类是一个配置类
    * 细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。
    * 注意:主配置类中可以不写,因为获取容器时通过ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);扫描主配置类。其余配置类需要写。并在主配置类中@ComponentScan({"com.zty"})添加扫描的类。
    *
    * ComponentScan
    * 作用:用于通过注解指定spring在创建容器时要扫描的包。
    * 属性:
    * value:它和basePackages的作用一样,都适用于指定创建容器时要扫描的包。
    * 我们使用此注解就等同于在xml中配置了:
    * <context:component-scan base-package="com.zty"></context:component-scan>
    *Bean
    * 作用:把当前方法的返回值作为bean对象存入spring的ioc容器中
    * 属性:
    * name:用于指定bean的id。默认值是当前方法的名称
    * 细节:
    * 当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象。
    * 查找的方式和Autowired注解的作用是一样的。先根据数据类型查找,再根据id查找。均在ioc容器中查找。
    *Import
    * 作用:导入其他的配置类.指定配置类的.class
    * 属性:
    * value:用于指定配置类的字节码。
    * 当我们使用Import的注解之后,有Import注解的类就是父配置类即主配置类,而导入的都是子配置类
    *PropertySource:
    * 作用:用于指定properties文件的位置
    * 属性:
    * value:指定文件的名称和路径。
    * 关键字:classpath,表示类路径下
    */
    @Configuration
    @ComponentScan({"com.zty"})
    @Import({})
    @PropertySource("classpath:jdbcConfig.properties")
    @EnableTransactionManagement 开启spring对注解事务的支持

    public class SpringConfiguration {
        @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 creatQueryRunner(DataSource dataSource){
    return new QueryRunner(dataSource);
    }

    /**
    * 创建数据源对象
    * @return
    */
    @Bean(name = "dataSourse")
    public DataSource creatDataSoure(){
    try {
    ComboPooledDataSource ds = new ComboPooledDataSource();
    ds.setDriverClass(driver);
    ds.setJdbcUrl(url);
    ds.setUser(username);
    ds.setPassword(password);
    return ds;
    }catch (Exception e){
    throw new RuntimeException(e);
    }
    }
    }
  • 相关阅读:
    java 多线程 Future callable
    nginx Access-Control-Allow-Origin css跨域
    maven 项目调试本地代码
    tomcat -ROOT 与webapps 的关系,关于部署的一些问题
    需求分析,挖掘背后的原因
    js 短信验证码 计时器
    总结一些小问题
    基于synchronized 或 ReadWriteLock实现 简单缓存机制
    java cookie 工具类
    309. 最佳买卖股票时机含冷冻期
  • 原文地址:https://www.cnblogs.com/ZTYCandy/p/10685583.html
Copyright © 2011-2022 走看看