网游活动聚合站 - 限时折扣与成就攻略

  • 首页
  • 特惠商城
  • 成就殿堂
  • 活动排行榜

(三)Spring 依赖注入

2026-08-14 18:41:50 | 活动排行榜

一、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复制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复制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复制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!

CS掉帧卡顿怎么办?一文详解原因与终极解决方案
佣金宝创业板开户条件
友情链接:
Copyright © 2022 网游活动聚合站 - 限时折扣与成就攻略 All Rights Reserved.