欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring框架的注入方式、注解

程序员文章站 2022-07-05 11:18:29
Spring笔记二依赖注入(DI):依赖注入(DI):控制反转:将创建对象、属性值的方式进行了翻转,从new、setxxx() 翻转为了从springIOC容器getBean()依赖注入:将属性值注入给了属性,将属性注入给了bean,将bean注入给了ioc容器;控制反转和依赖注入本就是一回事......

1、依赖注入(DI):

  • 控制反转:将创建对象、属性值的方式进行了翻转,从new、setxxx() 翻转为了从springIOC容器getBean()

  • 依赖注入:将属性值注入给了属性,将属性注入给了bean,将bean注入给了ioc容器;

  • 控制反转和依赖注入本就是一回事

      	依赖:bean对象的创建依赖于容器
      	注入:bean对象中的所有属性,由容器注入
    

2、注入方式

		<!--第一种,普通注入-->
        <!--<property name="name" value="zs"/>-->
        <property name="name">
            <value>zs</value>
        </property>
        
        <!--第二种,bean注入,ref-->
        <property name="address" ref="address"/>

        <!--第三种,数组注入-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
            </array>
        </property>

        <!--第四种,List注入-->
        <property name="hobbys">
            <list>
                <value></value>
                <value></value>
            </list>
        </property>

        <!--第五种,Map注入-->
        <property name="card">
            <map>
                <entry key="ID" value="123456"/>
                <entry key="cid" value="654321"/>
            </map>
        </property>

        <!--第六种,Set注入-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
            </set>
        </property>

        <!--第七种,null注入-->
        <property name="wife">
            <null></null>
        </property>

        <!--第八种,properties注入-->
        <property name="info">
            <props>
                <prop key="学号">50</prop>
                <prop key="性别">man</prop>
            </props>
        </property>

p命名空间注入????
引用加上

       xmlns:p="http://www.springframework.org/schema/p"
    <!--p命名空间注入,可以直接注入属性的值-->
    <bean id="user" class="User" p:name="zs" p:age="23"></bean>

c命名空间注入????

       xmlns:c="http://www.springframework.org/schema/c"
    <!--c命名空间注入,通过构造器注入-->
    <bean id="user2" class="User" c:age="18" c:name="ls"></bean>

需要有有参构造才能用

3、bean的作用域

Spring框架的注入方式、注解

3.1、单例模式(默认)

<bean id="user" class="User" scope="singleton"/>

3.2、原型模式(每次从容器中get的时候,都会产生一个新对象)

<bean id="user" class="User" scope="prototype"/>`在这里插入代码片`

3.3、其余request,session,application这些只能在Web开发中使用到

4、自动装配

在Spring中有三种装配的方式

  1. 在xm|中显示的配置
  2. 在java中显示配置
  3. 隐式的自动装配bean [重要]

4.1、ByName自动装配:自动在容器上下文中查找和自己set方法后的值对应beanid

<bean id="person" class="Person" autowire="byName">
    <property name="name" value="zs"/>
</bean>

4.2、ByType自动装配:自动在容器上下文中查找和自己类型相同的bean(类型要全局唯一,无id也行

<bean id="person2" class="Person" autowire="byType">
    <property name="name" value="zs"/>
</bean>

4.3、注解自动装配

  1. 导入约束:context
  2. 配置注解的支持:context:annotation-config/
<?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"
    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>
  1. 注解
  • @Autowired:直接在属性上加,也可以在set上。(可忽略编写set方法)

      前提是你这个自动装配的属性在I0C (Spring) 容器中存在,类型
    
  • @Autowired(required = false)

    //name可为空
    public Person(@Nullable String name) {
        this.name = name;
    }
  	该对象可为空
  • @Autowired @Qualifier(value = “dog22”)
	<bean id="dog11" class="Dog"/>
    <bean id="dog22" class="Dog"/>
		如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解[@Autowired]完成的时候,
		我们可以使用@Qualifier(value="xx" )去配置@Autowired的使用,指定一个唯一的bean对象注入
  • @Resource java的,不是spring的

      	先匹配name在匹配type
    
  • @Resource(name=“xxx”)

    <bean id="cat1" class="Cat"/>
    <bean id="cat2" class="Cat"/>
    @Resource(name = "cat1")
    private Cat cat; 
  • @Resource和@Autowired的区别:
  1. 都是用来自动装配的,都可以放在属性字段上
  2. @ Autowired通过byType的方式实现,而且必须要求这个对象存在! [常用]
  3. @ Resource默认通过byname的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况
    下,就报错! [常用]
  4. 执行顺序不同: @ Autowired通过byType的方式实现

5、使用注解开发

5.1 使用注解需要导入context约束,增加注解的支持

    <?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"
       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>

5.2 指定要扫描的包,包下的注解就会生效

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

Spring框架的注入方式、注解

@Component :组件,放在类上,说明这个类被Spring管理了,就是bean

@Value(“xx”):也可以写在set上,相当于<property id=" " value=" "/>
Spring框架的注入方式、注解

5.3 衍生注解

@Component有几个衍生注解,我们在web开发中,会按照mvc三层架构分层!

  • dao [@Repository]
  • service [@Service]
  • controller [@Controller]

这四个注解功能都是一样的, 都是代表将某个类注册到Spring中,装配Bean

5.4 作用域注解

@Scope(“xxx”)

5.5 小结

xml与注解:

  • xml更加万能,适用于任何场合维护简单方便
  • 注解不是自己类使用不了,维护相对复杂

xml与注解最佳实践:

  • xml用来管理bean;
  • 注解只负责完成属性的注入; .
  • 我们在使用的过程中,只需要注意-个问题: 必须让注解生效,就需要开启注解的支持

6、使用java的方式配置spring

	完全不使用spring的配置,全由java完成。
	JavaConfig是Spring的一个子项目,在Spring4之后,它成为了一个核心功能!

实体类????

package com.appconfig.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @Author: qsX
 * @Time: 2020-11-28 00:33
 * @Description:
 */
//说明这个类被Spring接管,注册到容器中
@Component
public class User {

    private String name;

    public String getName() {
        return name;
    }

    @Value("zs")//属性注入
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

配置文件????

package com.appconfig.config;

import com.appconfig.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

/**
 * @Author: qsX
 * @Time: 2020-11-28 01:11
 * @Description:
 */
@Configuration//被Spring容器托管,因为他也是一个@Component
@ComponentScan("com.appconfig.config")
@Import(MyConfig2.class)//合并配置文件
public class MyConfig {

    //注册一个bean,就相当于我们之前写的一个bean标签
    //这个方法的名字,就相当bean标签中的d属性
    //这个方法的返回值,就相当bean标签中的class属性
    @Bean
    public User user() {
        return new User();
    }
}

测试类????

import com.appconfig.config.MyConfig;
import com.appconfig.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Author: qsX
 * @Time: 2020-11-28 01:13
 * @Description:
 */
public class MyTest {
    public static void main(String[] args) {
        //注意这里末尾无引号
        //如果完全使用了配置方式,那么就需要用AnnotationConfigApplicationContext获取容器
        ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        User user = (User) context.getBean("user");
        System.out.println(user.getName());
    }
}

本文地址:https://blog.csdn.net/weixin_41852068/article/details/110153245

相关标签: Spring