天天看点

第四篇:Spring基础(Spring基础配置——依赖注入)

Spring框架本身有四大原则:

1)使用POJO进行轻量级和最小侵入式开发。

2)通过依赖注入和基于接口编程实现松耦合。

3)通过AOP和默认习惯进行声明式编程。

4)使用AOP和模板减少模式化代码。

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

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

依赖注入的主要目的是为了解耦,体现了一种“组合”的理念。

Spring IoC容器(ApplicationContext)负责创建Bean,并通过容器将功能类Bean注入到你需要的Bean中。Spring提供xml,注解,java配置,groovy配置实现Bean的创建和注入。

声明Bean的注解:

——@Component组件,没有明确的角色

——@Service 在业务逻辑层(service层)使用

——@Repository 在数据访问层(dao层)使用

——@Controller 在展现层(MVC——>Spring MVC)使用

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

——@Autowired:Spring提供的注解。对类成员变量,方法及构造函数进行标注,完成自动装配,来消除set,get方法。

——@Inject:JSR-330提供的注解

——@Resource:JSR-250提供的注解

@Autowired,@Inject,@Resource可注解在set方法或属性上,我习惯注解在属性上,优点是代码更少,层次更加清晰。

接下来演示基于注解的Bean的初始化和依赖注入,Spring容器类选用AnnotationConfigApplicationContext。

示例项目结构如下图:

第四篇:Spring基础(Spring基础配置——依赖注入)

(1)编写功能类的Bean:

package com.wisely.highlight_spring4.chl.di;
import org.springframework.stereotype.Service;
@Service

public class FunctionService {
    public String sayHello(String word) {
        return "Hello " +word+ " !";
    }

}
           

使用@Service注明当前Function类是Spring管理的一个Bean。

(2)使用功能类的Bean:

package com.wisely.highlight_spring4.chl.di;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UseFunctionService {
    @Autowired
    FunctionService functionService;

    public String SayHello(String word) {
        return functionService.sayHello(word);

    }

}
           

使用@Autowired将FunctionService的实体Bean注入到UseFunctionService中,让UseFunctionService具有FunctionService的功能。

(3)配置类。

package com.wisely.highlight_spring4.chl.di;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.wisely.highlight_spring4.chl.di")

public class DiConfig {

}
           

@Configuration声明当前类是一个配置类。

@使用ComponentScan会自动扫描所有使用声明Bean的类,并注册为Bean。

(4)运行

package com.wisely.highlight_spring4.chl.di;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =new AnnotationConfigApplicationContext(DiConfig.class);
        UseFunctionService useFunctionService=context.getBean(UseFunctionService.class);

        System.out.println(useFunctionService.SayHello("di"));

        context.close();

    }
}
           

运行结果如下:

第四篇:Spring基础(Spring基础配置——依赖注入)

继续阅读