spring基础系列之JavaConfig配置详解

发布时间 - 2026-01-11 02:21:19    点击率:

早以前,Spring推荐使用XML的方式来定义Bean及Bean之间的装配规则,但是在Spring3之后,Spring提出的强大的JavaConfig这种类型安全的Bean装配方式,它基于Java代码的灵活性,使得装配的过程也变得及其灵活。

使用JavaConfig来装配Bean拥有其自己的一套规则,我们在这里来看一看:

1、规则

规则一:@Configuration注解

我们在定义JavaConfig类时,都会在其上加注@Configuration注解,来表明这是一个配置类,@Configuration注解底层是@Component注解,而且这个注解会被AnnotationConfigApplicationContext来进行加载,AnnotationConfigApplicationContext是ApplicationContext的一个具体实现,代表依据配置注解启动应用上下文。

规则二:@ComponentScan注解

我们使用JavaConfig的目的是为了实现以前XML配置实现的功能,首先就是组件扫描功能,将我们使用特定注解标注的类统一扫描加载到Spring容器,这一功能就是依靠@ComponentScan注解来实现的,我们可以为其指定位置参数来指定要扫描的包。

规则三:@Bean注解

使用@Bean注解我们可以实现XML配置中手动配置第三方Bean的功能,这里我们使用方法来定义Bean,并在方法前面加注@Bean注解,表示要将该方法返回的对象加载到Spring容器中,这样就对我们的方法定义带来了一些限制,这些限制包括方法的大概格式:

1-方法带返回值,且返回类型为你要加载的第三方类类型

2-方法的名称为默认的Bean的name,如果要自定义Bean的name,可以使用@Bean注解的name属性。

3-要实现注入只需要将要注入的Bean的类型作为参数,调用该类的带参数的构造器构建这个Bean,或者采用第二种方式:先创建这个类的对象,然后调用该对象的set方法进行注入,以被注入的Bean的方法为参数

规则验证:

首先我们创建几个测试类

针对第一种注入方式:

1-StudentService

import org.springframework.stereotype.Service;

@Service
public class StudentService {
  public void study(){
    System.out.println("学生学习Java");
  }
}

2-TeacherService

import org.springframework.stereotype.Service;

@Service
public class TeacherService {
  
  private StudentService studentService;
  
  public TeacherService(StudentService studentService){
    this.studentService=studentService;
  }
  
  public void teach(){
    studentService.study();
  }
}

3-Config:这是针对第一种注入方式而设,需要在TeacherService 中定义带参数的构造器

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

@Configuration
//@ComponentScan
public class Config {
  
  @Bean(name="student")
  public StudentService studentService(){
    return new StudentService();
  }
  
  @Bean(name="teacher")
  public TeacherService teacherService(StudentService studentService){
    return new TeacherService(studentService);
  }
  
}

针对第二种注入方式:

1-StudentService

public class StudentService {
  
  public void study(){
    System.out.println("学生在学习Java");
  }
  
}

2-TeacherService

public class TeacherService {
    
  private StudentService studentService;

  public StudentService getStudentService() {
    return studentService;
  }

  public void setStudentService(StudentService studentService) {
    this.studentService = studentService;
  }
  
  public void teach(){
    studentService.study();
  }
  
}

3-Config:这是采用第二种注入方式:需要在TeacherService中提供set方法

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

@Configuration
public class Config {
  
  @Bean
  public StudentService student(){
    return new StudentService();
  }
  
  @Bean
  public TeacherService teacher(){
    TeacherService teacherService = new TeacherService();
    teacherService.setStudentService(student());
    return teacherService;
  }
  
}

4-测试类:TestMain

import java.util.Iterator;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestMain {

  public static void main(String[] args) {
    AnnotationConfigApplicationContext acac = new AnnotationConfigApplicationContext(Config.class);
    TeacherService teacher = acac.getBean(TeacherService.class);
    teacher.teach();
    Iterator<String> i = acac.getBeanFactory().getBeanNamesIterator();
    while(i.hasNext()){
      System.out.println(i.next());
    }
    acac.close();
  }

}

执行结果:

七月 14, 2017 4:10:56 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@7e6cbb7a: startup date [Fri Jul 14 16:10:56 CST 2017]; root of context hierarchy
学生学习Java
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
config
student
teacher
environment
systemProperties
systemEnvironment
org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry
messageSource
applicationEventMulticaster
lifecycleProcessor
七月 14, 2017 4:10:59 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@7e6cbb7a: startup date [Fri Jul 14 16:10:56 CST 2017]; root of context hierarchy

该测试结果中打印出的是Spring上下文中所有加载的Bean的名称(name)。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


# spring  # JavaConfig配置  # JavaConfig  # Spring中基于Java的配置@Configuration和@Bean用法详解  # Java语言读取配置文件config.properties的方法讲解  # 使用纯java config来配置spring mvc方式  # Spring 使用JavaConfig实现配置的方法步骤  # spring使用JavaConfig进行配置的方法  # 使用JavaConfig配置Spring的流程步骤  # Spring配置扩展之JavaConfig的使用小结  # 加载  # 这是  # 第二种  # 第三方  # 学生学习  # 第一种  # 自己的  # 的是  # 下午  # 几个  # 这一  # 你要  # 在这  # 推荐使用  # 会在  # 并在  # 这是一个  # 我们可以  # 带来了  # 自定义 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: Laravel如何处理CORS跨域问题_Laravel项目CORS配置与解决方案  Laravel的契約(Contracts)是什么_深入理解Laravel Contracts与依赖倒置  消息称 OpenAI 正研发的神秘硬件设备或为智能笔,富士康代工  阿里云高弹*务器配置方案|支持分布式架构与多节点部署  jimdo怎样用html5做选项卡_jimdo选项卡html5实现与切换效果【指南】  如何在阿里云虚拟服务器快速搭建网站?  Laravel如何使用Gate和Policy进行授权?(权限控制)  Laravel如何配置.env文件管理环境变量_Laravel环境变量使用与安全管理  如何在IIS中新建站点并配置端口与物理路径?  java中使用zxing批量生成二维码立牌  Laravel如何使用软删除(Soft Deletes)功能_Eloquent软删除与数据恢复方法  宙斯浏览器视频悬浮窗怎么开启 边看视频边操作其他应用教程  米侠浏览器网页背景异常怎么办 米侠显示修复  php嵌入式断网后怎么恢复_php检测网络重连并恢复硬件控制【操作】  阿里云网站搭建费用解析:服务器价格与建站成本优化指南  深圳网站制作平台,深圳市做网站好的公司有哪些?  详解免费开源的.NET多类型文件解压缩组件SharpZipLib(.NET组件介绍之七)  详解Android图表 MPAndroidChart折线图  手机网站制作与建设方案,手机网站如何建设?  三星网站视频制作教程下载,三星w23网页如何全屏?  如何在阿里云购买域名并搭建网站?  微信推文制作网站有哪些,怎么做微信推文,急?  Laravel如何与Inertia.js和Vue/React构建现代单页应用  Laravel怎么写单元测试_PHPUnit在Laravel项目中的基础测试入门  Laravel如何操作JSON类型的数据库字段?(Eloquent示例)  Laravel怎么导出Excel文件_Laravel Excel插件使用教程  英语简历制作免费网站推荐,如何将简历翻译成英文?  佛山企业网站制作公司有哪些,沟通100网上服务官网?  零基础网站服务器架设实战:轻量应用与域名解析配置指南  Laravel如何使用API Resources格式化JSON响应_Laravel数据资源封装与格式化输出  百度输入法全感官ai怎么关 百度输入法全感官皮肤关闭  网站制作免费,什么网站能看正片电影?  Laravel如何生成PDF或Excel文件_Laravel文档导出工具与使用教程  敲碗10年!Mac系列传将迎来「触控与联网」双革新  Android GridView 滑动条设置一直显示状态(推荐)  使用spring连接及操作mongodb3.0实例  PHP的CURL方法curl_setopt()函数案例介绍(抓取网页,POST数据)  实例解析angularjs的filter过滤器  PythonWeb开发入门教程_Flask快速构建Web应用  Laravel如何实现数据库事务?(DB Facade示例)  Laravel全局作用域是什么_Laravel Eloquent Global Scopes应用指南  html文件怎么打开证书错误_https协议的html打开提示不安全【指南】  如何快速生成高效建站系统源代码?  php打包exe后无法访问网络共享_共享权限设置方法【教程】  bing浏览器学术搜索入口_bing学术文献检索地址  Laravel任务队列怎么用_Laravel Queues异步处理任务提升应用性能  利用 Google AI 进行 YouTube 视频 SEO 描述优化  学生网站制作软件,一个12岁的学生写小说,应该去什么样的网站?  如何解决hover在ie6中的兼容性问题  Laravel事件监听器怎么写_Laravel Event和Listener使用教程