前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >(三)Spring 依赖注入

(三)Spring 依赖注入

作者头像
leehao
发布2025-02-11 12:59:25
发布2025-02-11 12:59:25
9300
代码可运行
举报
文章被收录于专栏:leehaoleehao
运行总次数:0
代码可运行

一、Spring框架本身有四大原则:

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

通过依赖注入和接口变成实现松耦合。

通过AOP和默认习惯进行声明式变成。

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

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

二、依赖注入

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

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

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

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

声明Bean的注解:

@Component 没有明确的角色

@Service 在业务逻辑层使用

@Repository 在数据访问层使用

@Controller 在展现层使用

注入Bean的注解:

@Autowired Spring提供的注解

@其他

示例:

①编写功能类Bean其中

代码语言:javascript
代码运行次数:0
复制
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。

②使用功能类Bean

代码语言:javascript
代码运行次数:0
复制
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的功能。

③  配置类+运行

代码语言:javascript
代码运行次数:0
复制
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!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-02-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档