spring IoC : DI依赖注入;自动装配;使用注解注入;使用Java的方式配置Spring

一、Spring IOC

  • IoC(Inversion of Control,控制反转)是一种设计思想。这是spring的核心,贯穿始终。所谓IoC,对于spring框架来说,就是由spring来负责控制对象的生命周期和对象间的关系。
  • Spring 的 IoC 设计支持以下功能:
    • 依赖注入
    • 依赖检查
    • 自动装配
    • 支持集合
    • 指定初始化方法和销毁方法
    • 支持回调某些方法(但是需要实现 Spring 接口,略有侵入)

二、DI(依赖注入)

2.1、构造器注入

  • 实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User {
    private int id;
    private String name;
}
  • 方式一:通过参数名给字段注入值
<bean id="user" class="com.study.pojo.User">
    <constructor-arg name="id" value="1"/>
    <constructor-arg name="name" value="张三"/>
</bean>
  • 方式二:通过参数类型给字段注入值

    注意:此方式要求参数类型唯一

bean id="user" class="com.study.pojo.User">
    <constructor-arg type="int" value="1"/>
    <constructor-arg type="java.lang.String" value="张三"/>
</bean>
  • 方式三:通过有参构造参数列表的索引给字段注入值
<bean id="user" class="com.study.pojo.User">
    <constructor-arg index="0" value="1"/>
    <constructor-arg index="1" value="张三"/>
</bean>

2.2、Set方式注入

  • 实体类
@Data
@ToString
public class Address {
    private String address;
}
@Data
@ToString
public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Set<String> games;
    private Map<String,String> cards;
    private String wife;
    private Properties info;
}
  • applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="address" class="com.study.pojo.Address">
        <property name="address" value="西安"/>
    </bean>

    <bean id="student" class="com.study.pojo.Student">

        <property name="name" value="张三"/>

        <property name="address" ref="address"/>

        <!--数组注入-->
        <property name="books">
            <array>
                <value>Java</value>
                <value>C</value>
                <value>PHP</value>
                <value>JS</value>
            </array>
        </property>

        <!--List-->
        <property name="hobbys">
            <list>
                <value>旅游</value>
                <value>敲代码</value>
            </list>
        </property>

        <!--Map-->
        <property name="cards">
            <map>
                <entry key="身份证" value="111111111111111111"/>
                <entry key="学生卡" value="11111111"/>
            </map>
        </property>

        <!--Set-->
        <property name="games">
            <set>
                <value>lol</value>
                <value>cf</value>
            </set>
        </property>

        <!--null-->
        <property name="wife">
            <null/>
        </property>

        <!--properties-->
        <property name="info">
            <props>
                <prop key="username">root</prop>
                <prop key="password">123456</prop>
            </props>
        </property>
    </bean>
</beans>

2.3、拓展方式注入

  • 使用p命令空间c命令空间注入,实体类为上例 2.1 中的 User 类
<?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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="user" class="com.study.pojo.User" p:name="张三" p:id="1"/>
    <bean id="user2" class="com.study.pojo.User" c:name="李四" c:id="2"/>
</beans>

三、Bean的自动装配

  • 自动装配是spring满足bean依赖的一种方式
  • spring会在上下文中自动寻找,并自动给bean装配属性

3.1、ByName

  • 保证所有bean的 id 唯一,且这个bean需要和自动注入的set方法的值一致
<bean id="bean" class="com.study.pojo.Bean" autowire="byName"/>

3.2、ByType

  • 保证所有bean的 class类型 唯一,且这个bean需要和自动注入属性的类型一致
<bean id="bean" class="com.study.pojo.Bean" autowire="byType"/>

四、使用注解开发

  • 注意:必须 导入spring-aop的包,必须在applicationContext.xml 文件中导入 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:component-scan base-package="com.study"/>
    <context:annotation-config/>

</beans>

4.1、注册类到spring中

  • @Component:加在类前
  • 衍生注解:
    • dao【@Repository】
    • service【@Service】
    • controller【@Controller】
  • 这四个注解功能完全一样,都是代表将某个类注册到spring中,装配Bean
@Component
public class User {...}

4.2、属性的注入

  • @Value(“value”)

  • 可以加在属性前,也可以加在**set()**方法前

@Value("张三")
private String name;


private int age;

public void setName(String name) {
    this.name = name;
}

@Value("1")
public void setAge(int age) {
    this.age = age;
}

4.3、使用注解实现自动装配

  • @Autowired:自动装配,需要满足上面 byNamebyType 的条件
  • @Qualifier:可与@Autowired配合使用,一般在**@Autowired**不能满足需求的时候使用,可指定需要装配的bean的 id
  • @Resource:自动装配,整合以上两种注解,即也可以指定 id
@Resource(name="dog")
private Dog dog;

@Autowired
@Qualifier("cat")
private Cat cat;

4.4、作用域

  • @Scope(“singleton”) 【spring 默认作用域
  • @Scope(“prototype”):原型
  • 加在类前面

五、使用Java的方式配置Spring

  • 使用 Java 类可以完全代替 applicationContext.xml 配置文件

  • 实体类

@Component
public class User {

    @Value("张三")
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • 配置类
//标记这是一个配置类
@Configuration
// 指定要扫描的包,这个包下的注解才会生效
//等同于:<context:component-scan base-package="com.study"/>
@ComponentScan("com.study.pojo")
//整合其他配置类,等同于:
//<import resource="beans.xml"/>
@Import(Config.class)
public class UserConfig {

    //注册一个bean , 就相当于我们之前写的一个bean标签
    //这个方法的名字,就相当于bean标签中的id属性
    //这个方法的返回值,就相当于bean标签中的class属性
    @Bean
    public User user(){
        return new User(); //返回要注入到bean的对象
    }
}
  • 测试类
public static void main(String[] args) {
    ApplicationContext context = new AnnotationConfigApplicationContext(UserConfig.class);
    User user = context.getBean("user", User.class);
    System.out.println(user);
}
发布了55 篇原创文章 · 获赞 23 · 访问量 4322

猜你喜欢

转载自blog.csdn.net/y_Engineer/article/details/102591011