| 注解 | 说明 |
| @Configuration | 用于指定当前类是一个 Spring 配置类,当创建容器时会从该类上加载注解 |
| @ComponentScan | 用于指定 Spring 在初始化容器时要扫描的包。作用和在 Spring 的 xml 配置文件中的 |
| @Bean | 使用在方法上,标注将该方法的返回值存储到 Spring 容器中 |
| @PropertySource | 用于加载.properties 文件中的配置,相当于 |
| @import | 用于导入其他配置类 |
| @RunWith | 替换原来的运行期spring容器 |
| @ContextConfiguration | 指定配置文件或配置类 |
①创建spring配置类
@Configuration //相当于之前的配置文件
@ComponentScan("com.*") //初始化容器扫描的包
@import(DataSourceConfiguration.class) //导入数据源配置类
public class SpringConfigration {
}
②创建数据库连接池信息
创建jdbc.properties配置文件
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/nie jdbc.username=root jdbc.password=root
创建数据库连接配置类
@PropertySource("classpath:jdbc.properties")
@Component("dataSourceConfiguration")
public class DataSourceConfiguration {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean("dataSource")
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
③测试是否连接成功
@Test
public void TestConfig() throws SQLException, PropertyVetoException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfigration.class);
DataSourceConfiguration dataSource = (DataSourceConfiguration) context.getBean("dataSourceConfiguration");
DataSource dataSource1 = dataSource.getDataSource();
System.out.println(dataSource1.getConnection());
DataSource dataSourceBean = (DataSource)context.getBean("dataSource");
System.out.println(dataSourceBean.getConnection());
}
2Spring整合Junit
在测试类中,每个测试方法都有以下两行代码:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) context.getBean("userDao");
这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。
Spring5支持整合SpringJunit的包,让SpringJunit负责创建Spring容器,但是需要将配置文件的名称告诉它,然后将需要进行测试Bean直接在测试类中进行注入
①导入spring集成Junit的坐标
② 使用 @Runwith注解替换原来的运行期,使用 @ContextConfiguration 指定配置文件或配置类 ③ 使用 @Autowired 注入需要测试的对象 ④进行测试对象是否注入org.springframework spring-test5.1.9.RELEASE junit junit4.13 test
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfigration.class})
//@ContextConfiguration("classpath:applicationContext.xml")
public class SpringJunitTest {
@Autowired
private UserService userService;
@Test
public void test01(){
userService.save();
}
}



