配置类介绍及创建方法

1. 完全注解开发

Spring 完全注解配置(Fully Annotation-based Configuration)是指通过 Java配置类 代码来配置 Spring 应用程序,使用注解来替代原本在 XML 配置文件中的配置。相对于 XML 配置,完全注解配置具有更强的类型安全性和更好的可读性。

XML配置文件中,主要有以下配置项:

  • bean标签配置IOC/DI
  • context:component-scan base-package 配置注解扫描包
  • context:property-placeholder引入外部文件

相对应,完全注解方式也有以下配置项:

  • 配置类代替XML配置文件,需要给类添加@configuration
  • bean标签方式用方法代替,并配合@bean注解完成第三方IOC注入
  • context:component-scan用@ComponentScan代替
  • context:property-placeholder用@PropertySource代替

可以看到,XML配置文件与配置类是一一对应的,这也便于我们的学习和理解。

2. 配置类

使用 @Configuration 注解将一个普通的类标记为 Spring 的配置类。

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

//标注当前类是配置类,替代application.xml    
@Configuration
//使用注解读取外部配置,替代 <context:property-placeholder标签
@PropertySource("classpath:application.properties")
//使用@ComponentScan注解,可以配置扫描包,替代<context:component-scan标签
@ComponentScan(basePackages = {"oeg.kkk.components"})
public class MyConfiguration {
    
}

测试创建IoC容器

// AnnotationConfigApplicationContext 根据配置类创建 IOC 容器对象
ApplicationContext iocContainerAnnotation = 
new AnnotationConfigApplicationContext(MyConfiguration.class);

可以使用 no-arg 构造函数实例化 AnnotationConfigApplicationContext ,然后使用 register() 方法对其进行配置。此方法在以编程方式生成 AnnotationConfigApplicationContext 时特别有用。以下示例演示如何执行此操作:

// AnnotationConfigApplicationContext-IOC容器对象
ApplicationContext iocContainerAnnotation = 
new AnnotationConfigApplicationContext();
//外部设置配置类
iocContainerAnnotation.register(MyConfiguration.class);
//刷新后方可生效!!
iocContainerAnnotation.refresh();

总结:

  • @Configuration指定一个类为配置类,可以添加配置注解,替代配置xml文件

  • @ComponentScan(basePackages = {“包”,“包”}) 替代<context:component-scan标签实现注解扫描

  • @PropertySource(“classpath:配置文件地址”) 替代 <context:property-placeholder标签

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值