(4)spring的annotation

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还是很方便的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值