Spring注入方式四:通过扫描类路径来把类对象注入Spring容器

前面讲过我们可以通过spring配置文件中通过<bean/>节点来注入一个对象,但是一个大型的项目会有成千上万了类也有可能,如果我们一个个通过<bean/>节点来注入的或那么配置文件将非常庞大和臃肿。查找和维护起来也不方便。Spring从2.5版本引入了组件自动扫描机制他可以再类路径下寻找标注了@Component, @Service,@Controllor,@Repository注解的类,并把他们注入到spring容器中,要使用自动扫描机制我们需要打开配置信息

  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xsi:schemaLocation=" http://www.springframework.org/schema/beans  
  5.        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  6.        http://www.springframework.org/schema/context  
  7.        http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  8.   
  9.     <context:component-scan base-package="com.web.service.controllor"/>  
  10.   
  11. </beans>  
其中base-package是我们需要扫面的包(含子包)

我们约定@Service用于标注业务层组件,@Controllor用于标注控制层组件,@Repository用于标注数据层组件 。而@Component用于标注我们不好归类那些组件,比如一些工具类。当然我们只是约定这些注解的含义以便于区分不同的类的性质,其实他们起到的作用都是一样的,即使你用@Contollor来注解业务层类而用@service注解数据层类,spring也可以把他们成功的注入到容器中。


那我们知道我们知道注入spring容器中的对象都有一个name,然后我们可以通过 applicationContext.getBean(beanName)来从容器中取得bean对象,那么我们可能就有这样的疑问说通过组件扫描的方式注入的bean如何得到其对象呢。

通过组件扫描的方式注入的方式bean如果我们没有在加注解的时候没有指定bean名称,那么spring就默认以类的名称且首字母为小写作为bean name,当然我们也可以在注解上定义bean的name

@Service("userBiz")

public class UserBizImpl implements UserBiz {

……
}




我们也可以用注解@Scope来设置bean的作用域

@Service("userBiz") @Scope("prototype")

public class UserBizImpl implements UserBiz {

……
}


我们也可以用注解@PostConstructor来设置bean的init-method,用@PreDestory来设置destory 方法

@Service("userBiz") @Scope("prototype")

public class UserBizImpl implements UserBiz {

    @PostContructor
    public void init() {
        System.out.println("init something");
    }

    @PreDestory
    public void destory() {
        System.out.println("destory something");
    }

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值