01-SpringBoot——Spring基础-依赖注入

来源:互联网 发布:模拟器mac版 编辑:程序博客网 时间:2024/06/08 15:34

01-SpringBoot——Spring基础-依赖注入


【博文目录>>>】


【项目源码>>>】


【依赖注入】

控制翻转(Inversion of Control-IOC)和依赖注入(dependency injection-DI)在Spring环境下是同等的概念,控制翻转是通过依赖注入实现的。所谓依赖注入是指容器负责创建对象和维护对象间的依赖关系,而不是通过对象本身去创建和解决自自己的依赖。依赖的主要目的是为了解耦,体现一种“组合”的理念。

无论是xml 自己置、注解配置,还是Java 配置,都被称为配置元数据,元数据是描述数据的数据。元数据本身不具备任何可执行的能力,只能通过外界代码来对这些元数据行解析后进行一些有意义操作。Spring 容器解析这些配置元数据进行Bean 初始化、配置和管理依赖。

声明Bean 的注解:

• @Component 组件,没有明确的角色。• @Service 在业务逻辑层( service 层)使用。• @Repository 在数据访问层( dao 层)使用。• @Controller 在展现层( MVC→Spring MVC )使用。

注入Bean 的注解,一般情况下通用。

• @Autowired: Spring 提供的注解。• @Inject: JSR“330 提供的注解。• @Resource: JSR”250 提供的注解。

@Auto wired 、@Inject、@Resource 可注解在set 方法上或者属性上,如果注解在属性上,代码更少、层次更清晰。


【样例实现】

/** * 使用@Service 注解声明当前FunctionService 类是Spring 管理的一个Beano 其中,使 * 用@Component 、@Service 、@Repository 和@Controller 是等效的,可根据需要选用。 * * Author: 王俊超 * Date: 2017-07-10 08:01 * All Rights Reserved !!! */@Servicepublic class FunctionService {    public String sayHello(String word) {        return "Hello " + word + " !";    }}
package com.example.spring.framework.di;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;/** * 使用@Service注解声明当前UseFunctionService 类是Spring 管理的一个Bean * <p> * Author: 王俊超 * Date: 2017-07-10 08:03 * All Rights Reserved !!! */@Servicepublic class UseFunctionService {    /**     * 使用@Autowired 将FunctionService 的实体Bean 注入到UseFunctionService 中,     * 让UseFunctionService 具备FunctionService 的功能,此处使用JSR嗣330的@Inject     * 注解或者JSR-250的@Resource 注解是等效的。     */    @Autowired    FunctionService functionService;    public String SayHello(String word) {        return functionService.sayHello(word);    }}
package com.example.spring.framework.di;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;/** * 使用@Configuration声明当前类是一个配置类 * 使用@ComponentScan,自动扫描包名下所有使用@Service@Component@Repository * 和@Controller 的类,并注册为Bean * * Author: 王俊超 * Date: 2017-07-10 08:01 * All Rights Reserved !!! */@Configuration@ComponentScan("com.example.spring.framework.di")public class DiConfig {}
package com.example.spring.framework.di;import org.springframework.context.annotation.AnnotationConfigApplicationContext;/** * Author: 王俊超 * Date: 2017-07-10 08:08 * All Rights Reserved !!! */public class Main {    public static void main(String[] args) {        // 1、使用AnnotationConfigApplicationContext 作为Spring 容器,接受输入一个配置类作为参数        AnnotationConfigApplicationContext context =                new AnnotationConfigApplicationContext(DiConfig.class);        // 2、获得声明自己置的UseFunctionService 的Bean        UseFunctionService useFunctionService = context.getBean(UseFunctionService.class);        System.out.println(useFunctionService.SayHello("world"));        context.close();    }}

【运行结果】

这里写图片描述

原创粉丝点击