-
前面学习了spring的配置方式来注入数据,进行一个回顾
-
简单的写一个Person类
package com.wang.domain;
public class Person {
private String name;
private String addr;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAddr(String addr) {
this.addr = addr;
}
public void setAge(int age) {
this.age = age;
}
public void show() {
System.out.println(name + "=" + addr + "=" + age);
}
}
- 配置上Person类型属性
<bean id="person" class="com.wang.domain.Person">
<property name="name" value="zhangsan"></property>
<property name="addr" value="wuhan"></property>
<property name="age" value="25"></property>
</bean>
- 在测试类中进行测试
@Test
//原始配置文件xml
public void test8() {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
Person person = (Person) app.getBean("person");
person.show();
}
-
上面是利用配置文件的方式进行注入,当一个项目庞大的时候需要进行切过来维护非常的不方便,spring提供了注解的方式可以完成相同效果
-
首先在配置xml中配置contex空间,如下配置,并配配置我们的包范围
<?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="com.wang"/>
</beans>
注解 | 说明 |
---|---|
@Component | 使用在类上用于实例化Bean |
@Controller | 使用在web层类上用于实例化Bean |
@Service | 使用在service层类上用于实例化Bean |
@Repository | 使用在dao层类上用于实例化Bean |
@Autowired | 使用在字段上用于根据类型依赖注入 |
@Qualifiter | 结合@Autowired一起使用用于根据名称进行依赖注入 |
@Resource | 相当于@Autowired+@Qualifiter,按照名称就进行注入 |
@Value | 注入普通属性 |
@Scope | 标注Bean的作用范围 |
- Component
@Component
@Scope("singleton")
//@Scope("prototype")
public class Demo {
public void show() {
System.out.println("show 已经运行....");
}
}
- Value
@Component
public class ValueDemo {
@Value("xiaoming")
private String name;
@Value("20")
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void show() {
System.out.println(name + "===" + age);
}
}
- Repository
@Repository("userDao")
public class UserDaoImpl implements UserDao {
public void show() {
System.out.println("show 已经运行");
}
}
- Service
@Service("userService")
public class UserServiceImpl implements UserService {
public void show() {
System.out.println("show 已经运行。。。。。");
}
}
- Controller|Autowired
@Controller("userController")
public class UserController {
@Autowired
private User user;
public void setUser(User user) {
this.user = user;
}
public void show() {
System.out.println("show 已经执行....");
}
public void run() {
user.show();
}
}
- Qualifier
@Controller
public class FruitController {
@Autowired
@Qualifier("banana")
private Fruit fruit;
public void setFruit(Fruit fruit) {
this.fruit = fruit;
}
public void show() {
fruit.show();
}
}