快上网专注成都网站设计 成都网站制作 成都网站建设
成都网站建设公司服务热线:028-86922220

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

Spring注解实现自动装配过程解析-创新互联

在IOC容器中学习相关注解(常用)

创新互联公司专注于企业成都全网营销推广、网站重做改版、安龙网站定制设计、自适应品牌网站建设、成都h5网站建设商城网站开发、集团公司官网建设、外贸网站建设、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为安龙等各大城市提供网站开发制作服务。

1. @Autowireda.作用对象:(官网解释)

1. You can apply the @Autowired annotation to constructors:

2.you can also apply the @Autowired annotation to "traditional" setter methods:

3.You can also apply the annotation to methods with arbitrary names and/or multiple arguments:

4.You can apply @Autowired to fields as well and even mix it with constructors:

5.It is also possible to provide all beans of a particular type from the ApplicationContext by adding the annotation to a field or method that expects an array of that type:

6.Even typed Maps can be autowired as long as the expected key type is String. The Map values will contain all beans of the expected type, and the keys will contain the corresponding bean names:等

总结一下就是: 可以在构造器,set方法,任意方法和属性上,数组上,String类型的Map上等。

Notes:1.@Autowired默认按类型装配(这个注解是属业spring的),默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false。

2.可以与@qualifier 共同使用, 当对象类型和名字发生冲突时,该注解可用于指定特定的对象。

@Autowired()
 @Qualifier("cat")

可以找到id="cat"的beanb.功能:它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。通过 @Autowired的使用来消除 set ,get方法。2.@Resourcea.功能: @Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按 byName自动注入

@Resource有两个属性是比较重要的,分是name和type,Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。

3.@Requireda.功能:@Required 注释应用于 bean 属性的 setter 方法,它表明受影响的 bean 属性在配置时必须放在 XML 配置文件中,否则容器就会抛出一个 BeanInitializationException 异常。下面显示的是一个使用 @Required 注释的示例。

这有一个很好的解释和例子关于@Required注解

使用@Autowired后的优点

原来我们需要手动注入之后才可以使用employee对象:

若没有进行手动注入,不会从测试代码中 获取到employee对象。

使用@Autowired之后

不需要手动注入。

只用在属性上进行@Autowired注释标注

Spring注解实现自动装配过程解析

在测试类中即可直接调用:

public class MyTest {
  public static void main(String[] args) {
   
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  
    Car car = (Car) context.getBean("car");
    car.getOwner().MyEmployment();
  
  }
}

另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


网页标题:Spring注解实现自动装配过程解析-创新互联
网址分享:http://6mz.cn/article/dodiss.html

其他资讯