Bean管理(3)


基于注解创建对象

  1. Component
  2. Service
  3. Controller
  4. Repository
  • 引入aop依赖包
  • 引入context命名空间
  • 开启组件扫描
1
2
3
4
5
<beans xmlns:context="http://www.springframework.org/schema/context" 
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="service"></context:component-scan>
</beans>
  • 创建UserService类
1
2
3
4
5
6
@Service	//或者@Component(value = "userService") 
public class UserService {
public void show() {
System.out.println("Nayuki");
}
}
  • 测试
1
2
UserService userService =context.getBean("userService", UserService.class);
userService.show();

基于注解注入属性

Autowired:根据类型进行自动装配

  • 创建UserDaoImpl类
1
2
3
4
5
6
7
@Repository
public class UserDaoImpl implements UserDao{
@Override
public void update() {
System.out.println("Nayuki!");
}
}
  • 创建UserService类
1
2
3
4
5
6
7
8
9
@Service
public class UserService {
@Autowired
UserDao userDao;
public void show() {
System.out.println("Nayuki");
userDao.update();
}
}

Qualifier:根据名称注入,和Autowired一起用

  • 创建UserDaoImpl类
1
2
3
4
5
6
7
@Repository(value = "userDaoImpl")
public class UserDaoImpl implements UserDao{
@Override
public void update() {
System.out.println("Nayuki!");
}
}
  • 创建UserService类
1
2
3
4
5
6
7
8
9
10
@Service
public class UserService {
@Autowired
@Qualifier(value = "userDaoImpl")
UserDao userDao;
public void show() {
System.out.println("Nayuki");
userDao.update();
}
}

Resource:根据类型和名称注入,不建议使用

  • 创建UserDaoImpl类
1
2
3
4
5
6
7
@Repository(value = "userDaoImpl")
public class UserDaoImpl implements UserDao{
@Override
public void update() {
System.out.println("Nayuki!");
}
}
  • 创建UserService类
1
2
3
4
5
6
7
8
9
@Service
public class UserService {
@Resource(value = "userDaoImpl")
UserDao userDao;
public void show() {
System.out.println("Nayuki");
userDao.update();
}
}

Value:注入普通类型

  • 创建UserService类
1
2
3
4
5
6
7
8
9
10
@Service
public class UserService {
@Value(value = "Nayuki")
String name;
@Value(value = "1")
int id;
public void show() {
System.out.println(id+"."+name);
}
}

完全注解开发

  • 创建配置类SpringConfig
1
2
3
4
@Configuration
@ComponentScan(basePackages = {"service"})
public class SpringConfig {
}
  • 创建UserService类
1
2
3
4
5
6
7
8
9
10
@Service
public class UserService {
@Value(value = "Nayuki")
String name;
@Value(value = "1")
int id;
public void show() {
System.out.println(id+"."+name);
}
}
  • 测试
1
2
3
4
5
6
@Test
public void testAdd(){
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
UserService userService =context.getBean("userService", UserService.class);
userService.show();
}