菜单

Resource注解区别,Spring注解分类和解释

2020年1月11日 - 4166am金沙下载

Spring对于Bean的信赖注入,帮忙多样表明情势:

1、@Inject

Spring使用基本的JavaBean来成功以前只或然由EJB完毕的专门的学问。中间使用了各类申明,甚至安顿文件。依附重视注入和调整反转,让开垦Java
Web 特别方便!

@Resource
javax.annotation
JSR250 (Common Annotations for Java)

@Inject
javax.inject
JSR330 (Dependency Injection for Java)

@Autowired
org.springframework.bean.factory
Spring

从没选用评释的时候,我们这么用<pre>public class UserManagerImpl
implements UserManager {private UserDao userDao;public void
setUserDao(UserDao userDao卡塔尔 {this.userDao = userDao;}}</pre>

4166am金沙下载,直观上看起来,@Autowired是Spring提供的笺注,别的多少个都是JDK本人内建的注释,Spring对那几个声明也举行了辅助。不过选取起来那三者到底有如何不一致吗?笔者通过艺术的测量试验,开掘一些有意思的性状。

那是JSTucson330中的标准,通过AutowiredAnnotationBeanPostProcessor类实现的依靠注入。

配备文件<pre><bean ><property name=”userDao”
ref=”userDao” /></bean><bean ><property
name=”sessionFactory” ref=”mySessionFactory”
/></bean></pre>

分别总括如下:

豆蔻梢头、@Autowired有个required属性,能够安排为false,这种景观下生龙活虎旦未有找到呼应的bean是不会抛格外的。@Inject和@Resource未有提供对应的陈设,所以必得找到不然会抛分外。

二、
@Autowired和@Inject基本是相近的,因为双方都以使用AutowiredAnnotationBeanPostProcessor来管理倚重注入。可是@Resource是个不等,它选择的是CommonAnnotationBeanPostProcessor来拍卖信赖注入。当然,两个都以BeanPostProcessor。

@Autowired和@Inject
- 默认 autowired by type
- 可以 通过@Qualifier 显式指定 autowired by qualifier name。
- 如果 autowired by type 失败(找不到或者找到多个实现),则退化为autowired by field name

@Resource
- 默认 autowired by field name
- 如果 autowired by field name失败,会退化为 autowired by type
- 可以 通过@Qualifier 显式指定 autowired by qualifier name
- 如果 autowired by qualifier name失败,会退化为 autowired by field name。但是这时候如果 autowired by field name失败,就不会再退化为autowired by type了。

TIPS Qualified name VS Bean name

在Spring设计中,Qualified name并分化样Bean
name,前面一个必需是唯后生可畏的,但是前面一个相符于tag或许group的效应,对特定的bean进行分类。能够直达getByTag(group卡塔尔的意义。对于XML配置的bean,能够透过id属性钦命bean
name(若无一些名,私下认可使用类名首字母小写),通过标签钦点qualifier
name:

<bean id="lamborghini" class="me.arganzheng.study.spring.autowired.Lamborghini">
    <qualifier value="luxury"/>
    <!-- inject any dependencies required by this bean -->
</bean>

假就算经过表明情势,那么能够透过@Qualifier注明钦点qualifier
name,通过@Named也许@Component(@Service,@Repository等)的value值钦定bean
name:

@Component("lamborghini")
@Qualifier("luxury")
public class Lamborghini implements Car {

}

或者

@Component
@Named("lamborghini")
@Qualifier("luxury")
public class Lamborghini implements Car {

}

同样,若无一点名bean
name,那么Spring会暗许是用类名首字母小写(蓝伯基尼=>lamborghini卡塔尔(قطر‎。

三、
通过Anotation注入重视的艺术在XML注入方式早先开展。假若对同三个bean的依赖同期使用了三种注入方式,那么XML的优先。不过不一致担小肠经过Anotation注入的借助无法注入XML中布局的bean,信赖注入是在bean的登记之后举办的。

四、近期的autowired by
type情势(笔者用的是3.2.3.RELEASE版本),Spring的AutowiredAnnotationBeanPostProcessor完成都以有”bug”的,也等于说@Autowired和@Inject都以有坑的(称之为坑,不称之为bug是因为平时是有意的。。)。那是源头线上的三个bug,也是这边著作的编写原因。现场如下:

application-context.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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">

    <context:annotation-config />

    <context:component-scan base-package="me.arganzheng.study" />

    <util:constant id="en"
        static-field="me.arganzheng.study.spring.autowired.Constants.Language.EN" />
    <util:constant id="ja"
        static-field="me.arganzheng.study.spring.autowired.Constants.Language.JP" />
    <util:constant id="ind"
        static-field="me.arganzheng.study.spring.autowired.Constants.Language.IND" />
    <util:constant id="pt"
        static-field="me.arganzheng.study.spring.autowired.Constants.Language.PT" />
    <util:constant id="th"
        static-field="me.arganzheng.study.spring.autowired.Constants.Language.TH" />
    <util:constant id="ar"
        static-field="me.arganzheng.study.spring.autowired.Constants.Language.AR" />
    <util:constant id="en-rIn"
        static-field="me.arganzheng.study.spring.autowired.Constants.Language.EN_RIN" />

    <util:map id="languageChangesMap" key-type="java.lang.String"
        value-type="java.lang.String">
        <entry key="pt" value="pt" />
        <entry key="br" value="pt" />
        <entry key="jp" value="ja" />
        <entry key="ja" value="ja" />
        <entry key="ind" value="ind" />
        <entry key="id" value="ind" />
        <entry key="en-rin" value="en-rIn" />
        <entry key="in" value="en-rIn" />
        <entry key="en" value="en" />
        <entry key="gb" value="en" />
        <entry key="th" value="th" />
        <entry key="ar" value="ar" />
        <entry key="eg" value="ar" />
    </util:map>

</beans>

其间static-田野(field卡塔尔应用的常量定义在如下类中:

package me.arganzheng.study.spring.autowired;

public interface Constants {

    public interface Language {
        public static final String EN = "CommonConstants.LANG_ENGLISH";
        public static final String JP = "CommonConstants.LANG_JAPANESE";
        public static final String IND = "CommonConstants.LANG_INDONESIAN";
        public static final String PT = "CommonConstants.LANG_PORTUGUESE";
        public static final String TH = "CommonConstants.LANG_THAI";
        public static final String EN_RIN = "CommonConstants.LANG_ENGLISH_INDIA";
        public static final String AR = "CommonConstants.LANG_Arabic";
    }
}

接下来豆蔻梢头旦大家在代码中如下宣示信赖:

public class AutowiredTest extends BaseSpringTestCase {

    @Autowired
    private Map<String, String> languageChangesMap;

    @Test
    public void testAutowired() {
        notNull(languageChangesMap);
        System.out.println(languageChangesMap.getClass().getSimpleName());
        System.out.println(languageChangesMap);
    }
}

Guess what,离奇的作业时有爆发了!

运营结果如下:

LinkedHashMap
{en=CommonConstants.LANG_ENGLISH, ja=CommonConstants.LANG_JAPANESE, ind=CommonConstants.LANG_INDONESIAN, pt=CommonConstants.LANG_PORTUGUESE, th=CommonConstants.LANG_THAI, ar=CommonConstants.LANG_Arabic, en-rIn=CommonConstants.LANG_ENGLISH_INDIA}

也便是说Map

严重: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@5c51ee0a] to prepare test instance [me.arganzheng.study.spring.autowired.AutowiredTest@6e301e0]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'me.arganzheng.study.spring.autowired.AutowiredTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.Map me.arganzheng.study.spring.autowired.AutowiredTest.languageChangesMap; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency [map with value type java.lang.String]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    ...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency [map with value type java.lang.String]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:843)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
    ... 28 more

debug了一下,发掘确实是Spring的八个bug。在DefaultListableBeanFactory的这几个法子出难题了:

protected Object doResolveDependency(DependencyDescriptor descriptor, Class<?> type, String beanName,
            Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
        ...     

        else if (Map.class.isAssignableFrom(type) && type.isInterface()) {
            Class<?> keyType = descriptor.getMapKeyType();
            if (keyType == null || !String.class.isAssignableFrom(keyType)) {
                if (descriptor.isRequired()) {
                    throw new FatalBeanException("Key type [" + keyType + "] of map [" + type.getName() +
                            "] must be assignable to [java.lang.String]");
                }
                return null;
            }
            Class<?> valueType = descriptor.getMapValueType();
            if (valueType == null) {
                if (descriptor.isRequired()) {
                    throw new FatalBeanException("No value type declared for map [" + type.getName() + "]");
                }
                return null;
            }
            Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType, descriptor);
            if (matchingBeans.isEmpty()) {
                if (descriptor.isRequired()) {
                    raiseNoSuchBeanDefinitionException(valueType, "map with value type " + valueType.getName(), descriptor);
                }
                return null;
            }
            if (autowiredBeanNames != null) {
                autowiredBeanNames.addAll(matchingBeans.keySet());
            }
            return matchingBeans;
        }
        ...
    }

重大在此一句:Map

严重: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@9476189] to prepare test instance [me.arganzheng.study.spring.autowired.AutowiredTest@2d546e21]
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency [map with value type java.lang.String]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=languageChangesMap)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:843)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486)
    ... 28 more

debug了风流倜傥晃,开掘跟未有一些名qualifie name是千篇黄金时代律的实施路线。不是点名了bean
name了吧?为啥如故autowired by
type呢?留心翻看了一下才意识。DefaultListableBeanFactory的doResolveDependency方法对第风流浪漫对项目做了不相同:

protected Object doResolveDependency(DependencyDescriptor descriptor, Class<?> type, String beanName,
            Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {

        Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
        if (value != null) {
            if (value instanceof String) {
                String strVal = resolveEmbeddedValue((String) value);
                BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null);
                value = evaluateBeanDefinitionString(strVal, bd);
            }
            TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
            return (descriptor.getField() != null ?
                    converter.convertIfNecessary(value, type, descriptor.getField()) :
                    converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
        }

        if (type.isArray()) {
            Class<?> componentType = type.getComponentType();
            Map<String, Object> matchingBeans = findAutowireCandidates(beanName, componentType, descriptor);
            if (matchingBeans.isEmpty()) {
                if (descriptor.isRequired()) {
                    raiseNoSuchBeanDefinitionException(componentType, "array of " + componentType.getName(), descriptor);
                }
                return null;
            }
            if (autowiredBeanNames != null) {
                autowiredBeanNames.addAll(matchingBeans.keySet());
            }
            TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
            return converter.convertIfNecessary(matchingBeans.values(), type);
        }
        else if (Collection.class.isAssignableFrom(type) && type.isInterface()) {
            Class<?> elementType = descriptor.getCollectionType();
            if (elementType == null) {
                if (descriptor.isRequired()) {
                    throw new FatalBeanException("No element type declared for collection [" + type.getName() + "]");
                }
                return null;
            }
            Map<String, Object> matchingBeans = findAutowireCandidates(beanName, elementType, descriptor);
            if (matchingBeans.isEmpty()) {
                if (descriptor.isRequired()) {
                    raiseNoSuchBeanDefinitionException(elementType, "collection of " + elementType.getName(), descriptor);
                }
                return null;
            }
            if (autowiredBeanNames != null) {
                autowiredBeanNames.addAll(matchingBeans.keySet());
            }
            TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
            return converter.convertIfNecessary(matchingBeans.values(), type);
        }
        else if (Map.class.isAssignableFrom(type) && type.isInterface()) {
            Class<?> keyType = descriptor.getMapKeyType();
            if (keyType == null || !String.class.isAssignableFrom(keyType)) {
                if (descriptor.isRequired()) {
                    throw new FatalBeanException("Key type [" + keyType + "] of map [" + type.getName() +
                            "] must be assignable to [java.lang.String]");
                }
                return null;
            }
            Class<?> valueType = descriptor.getMapValueType();
            if (valueType == null) {
                if (descriptor.isRequired()) {
                    throw new FatalBeanException("No value type declared for map [" + type.getName() + "]");
                }
                return null;
            }
            Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType, descriptor);
            if (matchingBeans.isEmpty()) {
                if (descriptor.isRequired()) {
                    raiseNoSuchBeanDefinitionException(valueType, "map with value type " + valueType.getName(), descriptor);
                }
                return null;
            }
            if (autowiredBeanNames != null) {
                autowiredBeanNames.addAll(matchingBeans.keySet());
            }
            return matchingBeans;
        }
        else {
            Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
            if (matchingBeans.isEmpty()) {
                if (descriptor.isRequired()) {
                    raiseNoSuchBeanDefinitionException(type, "", descriptor);
                }
                return null;
            }
            if (matchingBeans.size() > 1) {
                String primaryBeanName = determinePrimaryCandidate(matchingBeans, descriptor);
                if (primaryBeanName == null) {
                    throw new NoUniqueBeanDefinitionException(type, matchingBeans.keySet());
                }
                if (autowiredBeanNames != null) {
                    autowiredBeanNames.add(primaryBeanName);
                }
                return matchingBeans.get(primaryBeanName);
            }
            // We have exactly one match.
            Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
            if (autowiredBeanNames != null) {
                autowiredBeanNames.add(entry.getKey());
            }
            return entry.getValue();
        }
    }

设若是Array,Collection恐怕Map,则基于集合类四月素的门类来展开autowired
by
type(Map使用value的项目)。为何如此优越管理呢?原本,Spring是为着到达那样的指标:让您能够一次注入全数相符项指标实现,也正是说能够那样子注入:

@Autowired
private List<Car> cars;

大器晚成旦你的car有多个贯彻,那么都会注入进来,不会再报

org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No unique bean of type [me.arganzheng.study.spring.autowired.Car] is defined: 
expected single matching bean but found 2: [audi, toyota].

可是,上边的意况只要你用@Resource则不会有那个题目:

public class AutowiredTest extends BaseSpringTestCase {

    @Resource
    @Qualifier("languageChangesMap")
    private Map<String, String> languageChangesMap;

    @Test
    public void testAutowired() {
        assertNotNull(languageChangesMap);
        System.out.println(languageChangesMap.getClass().getSimpleName());
        System.out.println(languageChangesMap);
    }
}

符合规律运维:

LinkedHashMap
{pt=pt, br=pt, jp=ja, ja=ja, ind=ind, id=ind, en-rin=en-rIn, in=en-rIn, en=en, gb=en, th=th, ar=ar, eg=ar}

理当如此,你要是不点名@Qualifier(“languageChangesMap”State of Qatar,同一时间田野name不是languageChangesMap,那么依然长久以来报错的。

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency [map with value type java.lang.String]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.annotation.Resource(shareable=true, mappedName=, description=, name=, type=class java.lang.Object, authenticationType=CONTAINER, lookup=)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:843)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:438)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:416)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:550)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:150)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:303)
... 26 more

再正是,@Resource也能够兑现地方的List接纳全体达成:

public class AutowiredTest extends BaseSpringTestCase {

    @Resource
    @Qualifier("languageChangesMap")
    private Map<String, String> languageChangesMap;

    @Resource
    private List<Car> cars;

    @Test
    public void testAutowired() {
        assertNotNull(languageChangesMap);
        System.out.println(languageChangesMap.getClass().getSimpleName());
        System.out.println(languageChangesMap);

        assertNotNull(cars);
        System.out.println(cars.getClass().getSimpleName());
        System.out.println(cars);
    }
}

运营的妥妥的:

LinkedHashMap
{pt=pt, br=pt, jp=ja, ja=ja, ind=ind, id=ind, en-rin=en-rIn, in=en-rIn, en=en, gb=en, th=th, ar=ar, eg=ar}
ArrayList
[me.arganzheng.study.spring.autowired.Audi@579584da, me.arganzheng.study.spring.autowired.Toyota@19453122]

那是因为@Resource申明使用的是CommonAnnotationBeanPostProcessor微电脑,跟AutowiredAnnotationBeanPostProcessor不是同贰个笔者[/偷笑]。这里就不剖判了,感兴趣的同窗能够协调看代码切磋一下。

终极定论如下:

1、@Autowired和@Inject

autowired by type 可以 通过@Qualifier 显式指定 autowired by qualifier name(非集合类。注意:不是autowired by bean name!)
如果 autowired by type 失败(找不到或者找到多个实现),则退化为autowired by field name(非集合类)

2、@Resource

默认 autowired by field name
如果 autowired by field name失败,会退化为 autowired by type
可以 通过@Qualifier 显式指定 autowired by qualifier name
如果 autowired by qualifier name失败,会退化为 autowired by field name。但是这时候如果 autowired by field name失败,就不会再退化为autowired by type了

测量检验工程保存在GitHub上,是正经的maven工程,感兴趣的同班能够clone到地点运转测量检验一下。

@Inject使用

利用申明<pre>public class UserManagerImpl implements UserManager
{@Autowiredprivate UserDao userDao;}</pre>

补充

有同事指出Spring官方文书档案上有这么一句话跟笔者的结有一点点冲突:

However, although you can use this convention to refer to specific beans by name, @Autowired is fundamentally about type-driven injection with optional semantic qualifiers. This means that qualifier values, even with the bean name fallback, always have narrowing semantics within the set of type matches; they do not semantically express a reference to a unique bean id.

也正是说@Autowired尽管加了@Qualifier注脚,其实也是autowired by
type。@Qualifier只是一个约束词,过滤条件而已。重新跟进了一下代码,发掘真正是那样子的。Spring设计的这么些@Qualifier name 并不相通 bean
name。他有个别相仿于一个tag。可是若是那个tag是唯黄金时代的化,那么实际上效果上同意气风发bean
name。实现上,Spring是先getByType,得到list
candicates,然后再依照qualifier name实行过滤。

再定义三个Lamborghini,这里运用@Qualifier内定:

package me.arganzheng.study.spring.autowired;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
@Qualifier("luxury")
public class Lamborghini implements Car {

}

再定义贰个Rolls-royce,这里故意用@Named钦点:

package me.arganzheng.study.spring.autowired;

import javax.inject.Named;

import org.springframework.stereotype.Component;

@Component
@Named("luxury")
public class RollsRoyce implements Car {

}

测量检验一投注入定义的华侈车:

package me.arganzheng.study.spring.autowired;

import static junit.framework.Assert.assertNotNull;

import java.util.List;

import me.arganzheng.study.BaseSpringTestCase;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 * 
 * @author zhengzhibin
 * 
 */
public class AutowiredTest extends BaseSpringTestCase {

    @Autowired
    @Qualifier("luxury")
    private List<Car> luxuryCars;

    @Test
    public void testAutowired() {

        assertNotNull(luxuryCars);
        System.out.println(luxuryCars.getClass().getSimpleName());
        System.out.println(luxuryCars);
    }

}

运营结果如下:

ArrayList
[me.arganzheng.study.spring.autowired.Lamborghini@66b875e1, me.arganzheng.study.spring.autowired.RollsRoyce@58433b76]

补充:Autowiring modes

Spring支持多种autowire方式,当使用XML配置方式时,你能够透过autowire属性钦赐。

no. (Default) No autowiring. Bean references must be defined via a ref element. Changing the default setting is not recommended for larger deployments, because specifying collaborators explicitly gives greater control and clarity. To some extent, it documents the structure of a system.
byName. Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired. For example, if a bean definition is set to autowire by name, and it contains a master property (that is, it has a setMaster(..) method), Spring looks for a bean definition named master, and uses it to set the property.
byType. Allows a property to be autowired if exactly one bean of the property type exists in the container. If more than one exists, a fatal exception is thrown, which indicates that you may not use byType autowiring for that bean. If there are no matching beans, nothing happens; the property is not set.
constructor. Analogous to byType, but applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.

假诺接纳@Autowired、@Inject恐怕@Resource注明的时候,则有一点点复杂一些,会有四个破产退化进程,何况引进了Qualifier。可是基本原理是相仿。

常常来讲是@Inject的使用,不加@Named注脚,必要配备与变量名生机勃勃致就可以。

留神:使用AutoWired自动连线声明要求加多<pre><bean
/></pre>

@Inject
@Named("mongo")
private Mongo mongo;

也得以这么对艺术开展注明<pre>public class UserManagerImpl
implements UserManager {private UserDao userDao;@Autowiredpublic void
setUserDao(UserDao userDao卡塔尔 {this.userDao = userDao;}}</pre>

2、@Autowired

铺排文件<pre><bean /><bean ><property
name=”sessionFactory” ref=”mySessionFactory”
/></bean></pre>

用申明来向Spring容器注册Bean。那样就足以省非常多作业!开启阐明<context:component-scan
base-package=”cn.zxy.test”/>

@Autowired是Spring提供的讲解,通过AutowiredAnnotationBeanPostProcessor类完结的信赖注入,与@inject二者具备可交换性。

<context:annotationconfig
/>将隐式地向Spring容器注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、
PersistenceAnnotationBeanPostProcessor以至RequiredAnnotationBeanPostProcessor那4个BeanPostProcessor。

@Autowired的使用

三种注明

Spring 的依靠注明完毕Bean重视注入扶助如下三种注脚

Spring自带的一套依赖注入注脚1 @Required:信任检查;2
@Autowired:自动装配自动装配,用于替代基于XML配置的机关装配基于@Autowired的活动装配,默许是根据项目注入,能够用来构造器、字段、方法注入

@Resource的效果也便是@Autowired,只然则@Autowired按byType自动注入,而@Resource私下认可按byName自动注入罢了。

@Resource有两脾特性是相比较根本的,分别是name和type,Spring将@Resource声明的name属性深入分析为bean的名字,而type属性则深入分析为bean的类型。所以只要接受name属性,则动用byName的活动注入战略,而使用type属性时则使用byType自动注入计策。假若既不钦点name也不内定type属性,那个时候将透过反射机制使用byName自动注入计谋。

@Resource装配顺序假诺同期内定了name和type,则从Spring上下文中找到唯意气风发匹配的bean进行装配,找不到则抛出极度假诺钦定了name,则从左右文中查找名称相称的bean举办李装运配,找不到则抛出特别就算钦定了type,则在那早先后文中找到类型相称的唯风姿罗曼蒂克bean举办李装运配,找不到只怕找到八个,都会抛出极度假使既未有一点名name,又未有一点点名type,则自动依照byName情势举办李装运配;若无相称,则回降为二个原始类型实行相称,假如相配则自动装配;

@Resource申明在字段上,这样就不用写setter方法了,何况那几个表明是归于J2EE的,减少了与spring的耦合。那样代码看起就比较高雅。

3
@Value:注入SpEL表达式用于注入SpEL表达式,能够放置在字段方法或参数上@Value(value
= “SpEL表明式”卡塔尔国@Value(value = “#{message}”卡塔尔国4
@Qualifier:约束描述符,用于细粒度选用候选者@Qualifier约束描述符除了能依据名字实行注入,但能开展更加细粒度的决定什么采取候选者@Qualifier(value
= “节制标志符”卡塔尔(قطر‎

设若八个类都落成了二个接口作为bean,这时候有一点都不小希望就无法区分bean的切实项目,就须要Qualifier!

Java平台的公家评释,是Java EE
5标准之风流倜傥,在JDK6中暗许包涵那一个表明,从Spring2.5发端援救。1
@Resource:自动装配,默许依据项目装配,如若钦命name属性将基于名字装配,能够应用如下格局来钦赐@Resource(name
= “标志符”)字段或setter方法

2 @PostConstruct和PreDestroy:通过表明内定初步化和销毁方法定义

JS瑞鹰-330表明1 @Inject:等价于暗中同意的@Autowired,只是未有required属性2
@Named:钦点Bean名字,对应于Spring自带@Qualifier中的缺省的依据Bean名字注入情状3
@Qualifier:只对应于Spring自带@Qualifier中的扩大@Qualifier限制描述符申明,即只可以扩大使用,未有value属性

用于注入长久化上下文和尸体微机。

JPA注解@PersistenceContext@PersistenceUnit

@Service用于标明业务层组件

@Controller用于标记调节层组件(如struts中的action)

@Repository用于标明数据访谈组件,即DAO组件

@Component泛指组件,当组件不佳归类的时候,大家得以应用那几个评释实行标明。

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图