spring MVC——标签及注入

Spring2.5为我们引入了组件自动扫描机制,他可以在类路径底下寻找标注了@Component,@Service,@Controller,@Repository注解的类,并把这些类纳入进spring容器中管理。它的作用和在xml文件中使用bean节点配置组件时一样的。当然你要使用annotation就需要使用java5以上版本。

@Component是一个通用注解,用于说明一个类是一个spring容器管理的类。
除此之外,还有@Controller@Service@Repository是@Component的细化,这三个注解比@Component带有更多的语义,它们分别对应了表现层、服务层、持久层的类。
如果你只是用它们定义bean,你可以仅使用@Component,但是既然spring提供这些细化的注解,那肯定有使用它们的好处,不过在以下的例子中体现不出。

model层——mobile.java

DAO层——mobileDao.java(接口)、mobileDaoHibernate.java(实现前面接口)——@Repository

想要扫描Repository使之起作用要在applicationContext-dao.xml中配置如下

<!-- Activates scanning of @Repository -->
    <context:component-scan base-package="com.xx.dao"/>

@Repository("mobileDao")
public class MobileDaoHibernate extends GenericDaoHibernate<Mobile, Long> implements MobileDao {
	public MobileDaoHibernate() {
        super(Mobile.class);
    }
}
service层——mobileManage.java(接口)mobileManageImpl.java——@Service

首先在appplicationContext-service.xml中

<!-- Activates scanning of @Service -->
    <context:component-scan base-package="com.xx.service"/>
@WebService //java
public interface MobileManager extends GenericManager<Mobile, Long> {   }


@Service("mobileManager")	//spring
@WebService(serviceName = "MobileService", endpointInterface = "com.xx.service.MobileManager")//java
public class MobileManagerImpl extends GenericManagerImpl<Mobile, Long> implements MobileManager {
    MobileDao mobileDao;

    @Autowired
    public MobileManagerImpl(MobileDao mobileDao) {
        super(mobileDao);
        this.mobileDao = mobileDao;
    }}

@Autowired 与@Resource的区别:

 

1、 @Autowired与@Resource都可以用来装配bean. 都可以写在字段上,或写在setter方法上。

2、 @Autowired默认按类型装配(这个注解是属业spring的),默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用,如下











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值