Spring_注解①

  注解的目的 : 节省在应用程序上下文XML文件中显式配置bean工作。

  用@Component标识Spring bean

@Component注解是一个类型级的注释,能标识表示一个Spring bean(Spring 组件)的类。针对于应用程序的控制                   器、服务、数据访问对象采取特殊形式来注解。


1、@Controller注释控制器

@Service(value="fixedDepositService")
public class FixedDepositServiceImpl implements FixedDepositService{
    ...
}

这儿使用了@Service注释,因此此类表示一个Spring bean,注释接收一个value特性,这个value指定了value和Spring容            器注册的名称。value的作用与<bean>的id相同。

@Service(value="...")  =  @Service("...") , 如果不指定名称,则Spring假定bean名称与以小写字母开头的类的名称相同。

2、@Service注释服务

3、@Repository注释DAO

注意:使用上方三种注释使用@Component注释进行元注释,也就是它们本身还是使用@Component进行注释。


如果启动Spring类路径扫描功能的话可以使用Spring的context模式的<component-scan></component-scan>来启动类路               径扫描。

Source location - src/main/resources/META-INF/spring

<beans  xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="...http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">


    <context:component-scan base-package="com.zy.spring" />


</beans>

如果想要过滤用于向Spring容器自动注册的bean类,那么可以使用<component-scan>中的<resource-pattern>。这个特               性的默认值是**/*.class,这将意味着base-package特性指定的包下的所有bean类将自动注册。

<component-scan>中的<include-filiter>和<exclude-filter>提供了一种方法来指定用于自动注册的组件类,以及应忽略                   的类。

<beans ...>
    <context:component-scan base-package="com.zy.example">
        <context:include-filter type="annotation" expression="example.annotation.MyAnnotation"/>   

        <context:exclude-filter type="regex" expression=".*Details"/>       
    </context:component-scan>
</beans>

其中,<include-filiter>和<exclude-filter>定义了一个type特性,指定了用于过滤bean类的策略,expression指定了相应的             过滤器表达式。

解释上述:<include-filter>中指定了使用MyAnnotation类型级注解的bean类将自动注册到Spring容器中,而<exclude-                   filter>指定以名称以Details结尾的bean类将被<component-scan>忽略。

type特性可以接受的值

type特性的值描述
annotation如果特性为此,那么expression特性就需要指定为一个注释的完全限定类名(example.annotation.MyAnnotation),使用该注释的bean类满足过滤条件。
assignable如果特性为此,那么expression需要指定为一个可以被bean类分配到的类或者接口的完全限定名称
aspectj如果特性为此,那么expression需要指定为一个用于过滤bean类的AspectJ表达式
regex如果特性为此,那么expression需要为一个用于通过名称过滤bean类的正则表达式
custom如果特性为此,那么expression需要指定为一个用于过滤bean类的org.springframework.core.type.TypeFilter接口的实现

        因为我们没有在应用程序上下文XML文件中定义注释的bean类,所以无法使用<property>或者<constructor-arg>元素来指定他们的依赖项,所以需要使用@Autowired,@Inject等注释来指定被注释的bean类依赖性。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值