Spring控制反转-依赖注入

Spring控制反转-依赖注入


首先编写Pom文件

Spring-Context

Spring容器Jar包

Spring-Context.jar Spring容器


Spring 控制反转(Inversion of Control-IOC)-依赖注入(dependency injection-DI)

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

依赖注入常用注解

  • @Component 组件,没有明确的角色
  • @Controller 在展现层使用
  • @Service 在业务逻辑层使用
  • @Repository 在数据访问层使用
  • @Autowired 注入Bean(Spring提供的注解)
  • @Inject 注入Bean(JSR-330提供的注解)
  • @Resource 注入Bean(JSR-250提供的注解)

依赖注入-Demo

编写功能Bean
这里写图片描述
编写依赖者,通过@Autowired注解注入功能Bean
这里写图片描述

@Configuration//声明配置类
@ComponentScan("AOP")//扫描AOP包下的所有Spring注解
public class AppStart {
    public  static void main(String [] args){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();//创建Spring容器
        context.register(AppStart.class);//加载配置类
        context.refresh();//刷新Spring容器   加载配置类后必须刷新容器
        AOPController bean = context.getBean(AOPController.class);//从容器中获取Controller,as属性被自动注入
        bean.sayAWord("Holle!!");
        context.close();
    }
}    

运行结果
这里写图片描述

使用容器管理Bean-Demo

配置被管理Bean的有两种方式,注解配置和Java配置。
在配置业务逻辑Bean是使用注解式(@Controller,@Service,@Component,@Repository)
全局配置使用Java配置(数据库相关配置,MVC相关配置)

注解式配置(业务Bean的配置使用注解)

编写被管理的Bean

被注入的Bean
使用@Component注解声明他为Spring容器所管理的Bean

@Configuration//声明配置类
@ComponentScan("AOP")//扫描AOP包下的所有Spring注解
public class AppStart {
    public  static void main(String [] args){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();//创建Spring容器
        context.register(AppStart.class);//加载配置类
        context.refresh();//刷新Spring容器   加载配置类后必须刷新容器
        AutoBean bean = context.getBean(AutoBean.class);//从容器中获取到AutoBean类型的对象
        System.out.println(bean);
        context.close();//释放资源
    }
}

因为没有定义AutoBean.name属性的默认值所name 为空
这里写图片描述

Java配置

Java配置是通过@Configuration,@Bean实现的。
@Configuration来声明配置类,相当于Spring的XML配置文件。
@Bean声明在方法上面,表示此方法返回的是一个Bean对象

编写功能类

这里写图片描述

编写配置类

这里写图片描述
Conroller自动注入功能类。

@Configuration//声明配置类
@ComponentScan("AOP")//扫描AOP包下的所有Spring注解
public class AppStart {
    public  static void main(String [] args){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();//创建Spring容器
        context.register(AppStart.class);//加载配置类
        context.refresh();//刷新Spring容器   加载配置类后必须刷新容器
        AutoBean bean = context.getBean(AutoBean.class);//从容器中获取到AutoBean类型的对象
        System.out.println(bean);
        context.close();//释放资源
    }
}

运行结果
这里写图片描述

猜你喜欢

转载自blog.csdn.net/Holle_123/article/details/82595716