1. 程式人生 > 其它 >Spring新註解&Spring整合Junit

Spring新註解&Spring整合Junit

Spring新註解


作用:替換applicationContext中的

程式碼解析:

1.專案結構

2. DataSourceConfig

package com.hzc.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

/**
    @PropertySource("classpath:jdbc.properties")
    用於載入.properties 檔案中的配置
    相當於<context:property-placeholder location="classpath:jdbc.properties" />

    @Bean("dataSource")
    使用在方法上,標註將該方法的返回值儲存到 Spring 容器中
    相當於<bean id="dataSource" class="..DruidDataSource">...</bean>
 */
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfig {
    @Bean("dataSource")
    public DataSource getDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("${jdbc.driver}");
        dataSource.setUrl("${jdbc.url}");
        dataSource.setUsername("${jdbc.username}");
        dataSource.setPassword("${jdbc.password}");
        return dataSource;
    }
}

3.SpringConfig

package com.hzc.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
    @Configuration: 指定當前類是一個 Spring 配置類,當建立容器時會從該類上載入註解
    @ComponentScan("com.hzc"): 用於指定 Spring 在初始化容器時要掃描的包。
        作用和在 Spring 的 xml 配置檔案中的
        <context:component-scan base-package="com.hzc"/>一樣
    @Import(DataSourceConfig.class): 匯入其他配置類
        <import resource="classpath:other.xml" />


 */
@Configuration
@ComponentScan("com.hzc")
@Import(DataSourceConfig.class)
public class SpringConfig {

}

4.SpringTest

package com.hzc;

import com.hzc.config.SpringConfig;
import com.hzc.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringTest {
    @Test
    public void test1(){
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService service = (UserService) ac.getBean("userService");
        service.helloRun();
    }
}

Spring整合Junit

步驟:


NewSpringTest

package com.hzc;

import com.hzc.config.SpringConfig;
import com.hzc.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(value = "classpath:applicationContext.xml")
@ContextConfiguration(classes = {SpringConfig.class})
public class NewSpringTest {
    @Autowired
    private UserService userService;
    @Test
    public void test1(){
        userService.helloRun();
    }
}