未分类
2020-12-05 16:02:31
1822677238@qq.com
手机扫码查看
2020java框架教程:spring注解以及整合Junit
1.创建web项目
2.导包

3.导入配置文件log4j.properties
4.添加容器以及配置注解扫描:applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置注解扫描,指定要扫描的包 -->
<context:component-scan base-package="entity"/>
</beans>

5.配置注解扫描
<!–配置注解扫描,指定要扫描的包 –>
<context:component-scan base-package=”entity”/>
整合junit测试
1.导入spring-test包
2.创建实体类
在类的上方添加注解
@Component("users") 适用于所有组件
@Repository("users") 适用于持久层
@Service("users") 适用于service层
@Controller("users") 适用于控制层
等同于<bean name=”name” class=”entity.Users” />

3.创建测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RunWithTest {
@Resource(name = "users")
private Users users;
@Test
public void test(){
System.out.println(users);
}
}

4.指定对象的作用域是否是单例还是多例
@Scope(scopeName = "singleton") //二选一 @Scope(scopeName = "prototype")
5.set方式注入value值
a.在私有成员变量中注入
//注入
@Value("1")
private int id;
@Value("admin")
private String name;
@Value("5200")
private double salary;
@Autowired
private Car car;

b.在set方法注入


6.自动装配
@AutoWired
使用@AutoWired进行自动装配,按照对象的类型进行自动装配
@Component
public class Car {
@Value("摩拜单车")
private String name;
@Value("black")
private String color;
}
public class Users {
@Autowired 自动装配
private Car car;
}
自动装配存在的问题:如果一个类型有多个对象,那么可以采用以下的方式
先在配置文件中添加
<bean name="car1" class="entity.Car">
<property name="name" value="保时捷"/>
<property name="color" value="red"/>
</bean>
<bean name="car2" class="entity.Car">
<property name="name" value="捷达"/>
<property name="color" value="white"/>
</bean>
A.使用@Qualifier指定具体的对象
@Autowired
@Qualifier("car1")
private Car car;
B.使用 @Resource 指定具体的对象
@Autowired @Resource(name="car2") private Car car;
7.初始化方法和销毁方法
@PostConstruct
public void init(){
System.out.println("初始化");
}
@PreDestroy
public void destroy(){
System.out.println("销毁");
}




发表回复