Spring中常用的一些注解

来源:互联网 发布:淘宝差评能追评吗 编辑:程序博客网 时间:2024/05/22 07:57

spring中有的比较重要的注解老是忘记,可能是代码敲的不多吧,先把它记下来,以备以后忘记了可以来查。


1、@Component

使用注解Component时,我们一般在spring的配置文件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"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"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        http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop-2.5.xsd        http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"><context:annotation-config /><context:component-scan base-package="com.pm" /><!-<bean id="userLoginDao" class="com.pm.dao.UserLoginDao"></bean>-></beans>


其中<context:annotation-config />的作用是向spring容器注册,

        可以参考:http://mushiqianmeng.blog.51cto.com/3970029/723880/。


<context:component-scan base-package="com.pm" />配置解析:

        使用ClassPathXmlApplicationContext("bean.xml")初始化beans.xml的时候,或者说初始化spring配置文件的时候,会自动扫描com.pm下的所有包,若发现有@component,则将该类初始化为一个对象,对象的key为@component("name")中指明的name,若不指明,则默认为类的名字首字母小写;当调用ctx.getBean("userService")时,则查看容器是否有一个名字为userService的bean;如有则在初始化这个类得过程中,如果发现@Resource(name=”u”);则查看容器是否有名字叫u的bean,若有则将u注入到方法参数中,而后参数就会传人方法内,当然也就注入了成员变量里。

参考链接:http://heavengate.blog.163.com/blog/static/20238105320127234165489/

<bean id="userLoginDao" class="com.pm.dao.UserLoginDao">
</bean>
作用是在beans.xml初始化时生成一个为UserLoginDao的bean,其作用和@Component差不多。


2、@Resource

主要用在属性的setxxx()上,@Resource默认按 byName自动注入,@Resource有两个属性是比较重要的,分是name和type(type用到时再查)。

@Resource(name="xxx")作用是赋值,即将beans.xml中的名字为“xxx”的bean注入到该属性。



未完待续...






0 0
原创粉丝点击