作用:替换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(); } }
步骤:
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(); } }