天天看點

spring ioc 的常用給配置和注解資料庫配置檔案redis配置檔案使用配置類測試的方法

資料庫配置檔案

## db.properties
## 加上jdbc.字首原因是 怕回頭你還有些業務 需要使用 重名的屬性名!!!
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db
jdbc.username=root
jdbc.password=root
           

redis配置檔案

redis.host=localhost
redis.port=6379
#最大空閑連接配接數
redis.maxIdle=30
redis.maxTotal=50
redis.minIdle=10
redis.maxWaitMillis=2000
           

pom.xml

<dependencies>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>

    <!-- 接觸到的資料庫連接配接池 c3p0 基本沒人用了 性能比較差-->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.5</version>
    </dependency>

    <!--阿裡的 druid連接配接池 号稱性能非常高-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.18</version>
    </dependency>

    <!--号稱世界第一 hikari 光之子 -->
    <dependency>
      <groupId>com.zaxxer</groupId>
      <artifactId>HikariCP</artifactId>
      <version>3.4.2</version>
    </dependency>


    <!--mysql的驅動-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>

    <!--導入spring 關于測試用例jar包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>
    <!--有個要求 junit測試要版本号4.12 之上-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>3.1.0</version>
    </dependency>
  </dependencies>

           

beans.xml

<!--導入外部屬性檔案 classpath 類路徑下哪裡-->
    <!--命名空間使用 可以由提示的!!!!-->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>


    <!--如果一個類 不是咱們寫 您就是老老實實配置 -->
    <!--注入 老牌的c3po-->
    <bean id="datasource01" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>


    <!--druid連接配接池-->
    <bean id="datasource02" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>

    </bean>

    <!--hikari資料庫連接配接池  後面就是springboot架構 預設資料庫連接配接池-->
    <bean id="datasource03" class="com.zaxxer.hikari.HikariDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--
        非常關鍵的一步  告訴spring架構 掃描哪些包下 有可能存在 我們需要元件對象
        component-scan:元件掃描的意思
        如果存在多個包 中間以逗号分隔

        可以掃描父包 但是不建議  原因:所謂掃描 底層就是挨個周遊檔案夾 檢視那個類 都掃描性能會差!!
        建議你精确到您需要的包名
    -->
    <context:component-scan base-package="com.dao,com.service"></context:component-scan>


           
//用在dao的實作類上
@Component
@Repository
public class ProductDaoImpl  implements ProductDao{
	//注入屬性  不用寫set.. 方法
 	 @Autowired
    private DataSource dataSource;
    .....
}



//用在service的實作類上
@Component
//"别名"     一般不起别名,使用預設
@Service("abc")
public class ProductServiceImpl implements ProductService{.....}

//在測試類中直接調用
 context.getBean(ProductService.class);
 

           

使用配置類

DatasourceConfig.java

/**
 * <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
 * 跟它是一個作用
 */
@PropertySource("classpath:db.properties")
public class DatasourceConfig {

    /**
     * 就是讀取properties裡面值 指派給屬性!!!
     */
    @Value("${jdbc.driver}")
    private String driverClassname;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;




    //如果有一些 不是我們寫的類  我們可以使用方法來做

    /**
     * 方法名随便起 最好見名知意
     * 方法的傳回值 是你希望放入容器對象
     *
     * 方法上必須加上注解 @Bean
     *
     */
    @Bean
    public DataSource generateDatasource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassname);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        return dataSource;
    }
}

           

Redis.java

@PropertySource("classpath:redis.properties")
public class RedisConfig {
    @Value("${redis.host}")
    private String host;
    @Value("${redis.port}")
    private int port;


    @Value("${redis.maxIdle}")
    private int maxIdle;
    @Value("${redis.maxTotal}")
    private int maxTotal;
    @Value("${redis.minIdle}")
    private int minIdle;
    @Value("${redis.maxWaitMillis}")
    private int maxWaitMillis;
    @Bean
    public GenericObjectPoolConfig createRedisConfig(){
        GenericObjectPoolConfig config=new JedisPoolConfig();

        config.setMaxIdle(maxIdle);
        config.setMaxTotal(maxTotal);
        config.setMinIdle(minIdle);
        config.setMaxWaitMillis(maxWaitMillis);
        return config;
    }

    /**
     * 如果你需要用另外一個在容器放着的對象 隻要把寫到參數就可以了
     *
     */
    @Bean
    public JedisPool createJedisPool(GenericObjectPoolConfig config){


        //建立這個jedis連接配接池代碼
        JedisPool pool = new JedisPool(config,host,port);

        return pool;

    }



}

           

springconfig.java

/**
 *  這個類 就要替代咱們那個xml了
 *  @Configuration 表示這個類是spring的配置檔案類
 *
 *
 */
@Configuration
/**
 * <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
 * 跟它是一個作用
 */
//@PropertySource("classpath:db.properties")
/**
 * <context:component-scan base-package="com.itheima.dao,com.itheima.service,com.itheima.xyz"></context:component-scan>
 * 跟它一個作用
 */
@ComponentScan({"com.itheima.dao","com.itheima.service","com.itheima.xyz"})
/**
 * 把拆出去的配置類 到如核心配置類中
 */
@Import({DatasourceConfig.class,RedisConfig.class})
public class SpringConfig {


}

           

測試的方法

方法一

public class ProductTest {
    /**
     * 測試一下擷取productService對象
     */
    @Test
    public void test01() {
        //建立一個spring的容器對象

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        ProductService productService = context.getBean(ProductService.class);
        System.out.println("測試擷取ProductService:"+productService);
    }
}

           

方法二

/**
 * 運作環境交給了 spring控制
 */
@RunWith(SpringJUnit4ClassRunner.class)
/**
 * 告訴spring配置類是哪個類!!!
 */
@ContextConfiguration(classes = SpringConfig.class)
public class UserTest {

    @Autowired
    private UserService userService;



    /**
     * 測試是邏輯操作 登入操作
     */
    @Test
    public void test03(){
        //UserService userService = context.getBean(UserService.class);

        userService.login("zhangsan","123");

    }

    /**
     * 測試 儲存操作
     */
    @Test
    public void test04(){
        //UserService userService = context.getBean(UserService.class);

        userService.save(new User());

    }