beans.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:annotation-config/>
<context:component-scan base-package="spring"/>
</beans>
1.<context:annotation-config/>----打开spring的annotation
2.<context:component-scan base-package="spring"/>----设置从前缀为spring的包中找
@Component("UserAction")
//@Controller("UserAction")
@Scope("prototype")
public class UserAction {
private User user;
private int id;
private UserService UserService;
public UserAction() {
}
public UserAction(UserService userService) {
this.UserService = userService;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public UserService getUserService() {
return UserService;
}
@Resource
public void setUserService(UserService userService) {
this.UserService = userService;
}
public void add() {
UserService.add(user);
}
public void delete() {
UserService.delete(id);
}
public void load() {
UserService.delete(id);
}
}
@Component("userDao")相当于<bean id="userDao" class="spring.dao.UserDao">
@Scope("prototype")多例
@Resource() 自动完成依赖注入,默认通过byName(加在setXX前面)
@autoWired 默认通过类型(不建议使用,一个类有多个类型一样的属性就报错)
@Repository 一般用于dao的注入
@service 业务层,完成对service类的注入
@controller 控制层,完成对action类的注入
最佳实践;项目很大不建议使用annotation,项目很大,很多类,不会按照包分类,而是按照模块分,建议用xml
项目小的话用annotation还是很方便的。