spring注解开发---beans注入

发布时间 2023-10-06 10:53:57作者: 哲_心

万能xml开头:

<!--导入p,c命名空间 context注解 -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config/> <!--必须使用这个标签,才能使用注解-->

原先使用beans.xml的方法

    <bean name="cat" class="zhe.xin.pojo.Cat"/>
    <bean name="dog" class="zhe.xin.pojo.Dog"/>
    <bean name="person" class="zhe.xin.pojo.Person">
        <property name="dog" ref="dog"/>
        <property name="cat" ref="cat"/>
        <property name="name" value="小哲"/>
    </bean>

使用注解后:

只需要这样注册xml:

 <bean name="cat" class="zhe.xin.pojo.Cat"/>
 <bean name="dog" class="zhe.xin.pojo.Dog"/>
 <bean name="person" class="zhe.xin.pojo.Person"/>

在person类里:

public class Person {
    @Autowired
    Dog dog;
    @Autowired
    Cat cat;
    String name;
//...get
}

等同于:

1 <bean name="person" class="zhe.xin.pojo.Person" autowire="byName"/>

ps:自动寻找beans里的name等于类里的变量名的标签

使用了 @Autowired 注释后,

  1. 不需要在xml里配置: <property/>
  2. 类里不需要写set方法
  3. @Autowired只能匹配byName

假如beans里的没有名字相匹配:

    <bean name="dog1" class="zhe.xin.pojo.Dog"/>

则java代码要加入

    @Qualifier("dog2")
    @Autowired
    Dog dog;

总结: @Autowired 可以自动自动装配,但是默认用byName匹配, 如果没有匹配的name就要加入 @Qualifier("name")进行匹配类

 


下面有个简单的方法:

使用 :@Resource注解

 在注释中可以看到这是Java提供的方法

他可以弥补 @Autowired 的不足, 一个@Resource可以代替@Autowired 和@Qualifier("name")两个注解

他首先匹配byName 若没有在匹配byType


学习到的内容:

@Autowired 可以自动自动装配,但是默认用byName匹配
@Qualifier("name") 如果@Autowired没有匹配的name,就要加入此注释进行匹配类
@Resource注解:首先匹配byName 若没有在匹配byType,一个@Resource可以代替@Autowired 和@Qualifier("name")两个注解

 

2023-10-06  10:44:27