1:注解方式来进行spring中的bean配置十分的方便,可以极大的简化applicationContext.xml中的代码行数
但是可能带来后期维护和性能相对于xml配置比较差
2:注解方式中的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"> //注解扫描 bese-package 基于某个包下 <context:component-scan base-package="com.yuwenhui.annotation"> </context:component-scan>
3:数据访问层(dao、repository)的实现类代码
不需要在接口上写注释
@Repository("userRepository") public class UserRepositoryImpl implements IUserRepository { @Override public void saveUser() { System.out.println("User Repository "); } }
4:业务逻辑层(service)的实现类代码
@Service("userService") public class UserServiceImpl implements IUserService { @Resource(name = "userRepository") private IUserRepository userRepository; @Override public void saveUser() { System.out.println("User Service"); userRepository.saveUser(); } public IUserRepository getUserRepository() { return userRepository; } public void setUserRepository(IUserRepository userRepository) { this.userRepository = userRepository; } }
5:控制层(Controller)层的代码
@Controller("userController")
public class UserController {
@Resource(name = "userService")
private IUserService userService;
@Value(value = "余文辉")
private String name;
public void saveUser(){
System.out.println("User Controller");
userService.saveUser();
}
public IUserService getUserService() {
return userService;
}
public void setUserService(IUserService userService) {
this.userService = userService;
}
public void sayName(){
System.out.println("我的名字:"+this.name);
}
}
6:注意点
@Resource 通过名称进行装配,名称可以通过name进行指定(该注释属于J2EE,不属于spring内的,是在 javax.annotation包下)
@Autowired 默认通过类型进行指定,当类型存在多个时,通过将类名的首字母小写,来进行name装配,如果不存在则报错
@Qualifier 通过name进行装配,语法为:
@Qualifier("name")
一般和Autowired进行联合使用