一 @Nullable 注解
1.1概念
import org.springframework.lang.Nullable;
目的 有些值为空可能会报空指针
1.2 使用
@Nullable 注解可以使用在方法上面,属性上面,参数上面,表示方法返回可以为空,属性值可以为空,参数值可以为空.
二 GenericApplicationContext
2.1目的
需要new一个新对象的时候,此对象无法交给Spring进行管理,
函数式风格创建对象,就可以交给 spring 进行管理
2.2 使用
public void testGenericApplicationContext() {
//1 创建 GenericApplicationContext 对象
GenericApplicationContext context = new GenericApplicationContext();
//2 调用 context 的方法对象注册
context.refresh();
context.registerBean("user1",User.class,() -> new User());
//3 获取在 spring 注册的对象 com.remained.User全类名
// User user = (User)context.getBean("com.remained.User");
User user = (User)context.getBean("user1");
System.out.println(user);
}
三 整合Junit
需要引入的依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.6.RELEASE</version>
<scope>test</scope>
</dependency>
3.1 整合Junit4
原因:每次测试时 都需要创建其ClassPathXmlApplicationContext对象加载配置文件
ClassPathXmlApplicationContext co = new ClassPathXmlApplicationContext("bean2.xml");
UserService user = co.getBean("userService", UserService.class);
user.test();
通过注解加载配置文件
@RunWith(SpringJUnit4ClassRunner.class) //单元测试框架
@ContextConfiguration("classpath:bean1.xml") //加载配置文件
public class JTest4 {
@Autowired
private UserService userService;
@Test
public void test() {
userService.accountMoney();
}
}
3.2 整合Junit5(比着4相当于减少了部分代码)
第一种
@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:bean1.xml")
public class JTest5 {
@Autowired
private UserService userService;
@Test
public void test1() {
userService.accountMoney();
}
}
第二种
//使用一个复合注解替代上面两个注解完成整合
@SpringJUnitConfig(locations = "classpath:bean1.xml")
public class JTest5 {
@Autowired
private UserService userService;
@Test
public void test1() {
userService.accountMoney();
}
}