Spring依赖注入(三)

Spring框架本身有四大原则:

使用POJO进行轻量级和最小侵入式开发。
通过依赖注入和接口变成实现松耦合。
通过AOP和默认习惯进行声明式变成。
使用AOP和模板减少模式化代码。

Spring所有功能和实现都是基于此四大原则的。

依赖注入

常说的IOC控制翻转和DI依赖注入在Spring环境下是等同的概念,控制翻转是通过依赖注入实现的。所谓的依赖注入指的是容器负责创建对象和维护对象之间的依赖关系,而不是通过对象本身负责自己的创建和解决自己的依赖。

依赖注入的主要目的是为了解耦,体现了 一种“组合”的理念。如类A+类B,而不是类A继承类B。好处是,组合会大大降低耦合性。

Spring IoC容器(ApplicationContext)负责创建Bean,通过容器将功能类Bean注入到你需要的Bean中。

Spring提供使用xml、注解、Java配置、groovy配置实现Bean的创建和注入。

声明Bean的注解:

1
2
3
4
5
6
7
@Component 没有明确的角色

@Service 在业务逻辑层使用

@Repository 在数据访问层使用

@Controller 在展现层使用

注入Bean的注解:

1
2
@Autowired //Spring提供的注解  
@其他

示例

  1. 编写功能类Bean其中

    1
    2
    3
    4
    5
    6
    7
    8
    package com.test.service;
    import org.springframework.stereotype.Service;
    @Service
    public class HelloServcie {
    public String sayHello(String word) {
    return "Hello " + word + "!";
    }
    }

    @Service注解声明当前HelloService类是Spring管理的一个Bean。

  2. 使用功能类Bean

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    package com.test.controller;

    import com.test.service.HelloServcie;
    import org.springframework.beans.factory.annotation.Autowired;
    @Controller
    public class HelloController {
    @Autowired
    HelloServcie helloServcie;

    public String SayHello(String word) {
    return helloServcie.sayHello(word);
    }
    }

@Service注解声明当前HelloController类是Spring管理的一个Bean。
@Autowire将HelloService的实体注入到HelloController中,让HelloController具备HelloService的功能。

  1. 配置类+运行
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    package com.test;
    import com.test.controller.HelloController;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    @Configuration
    @ComponentScan("com.test")
    public class App {
    public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);
    HelloController helloController = context.getBean(HelloController.class);
    System.out.println(helloController.SayHello("Tom"));
    context.close();
    }
    }
    @Configuration声明当前类是一个配置类。

@ComponentScan,自动扫描包名下所有使用@Service、@Component、@Repository和@Controller的类,并注册为Bean。

结果如下:Hello Tom!


Spring依赖注入(三)
https://leehoward.cn/2019/10/17/Spring依赖注入(三)/
作者
lihao
发布于
2019年10月17日
许可协议