Spring使用注解代替配置文件

本文介绍了如何使用Spring注解替代XML配置,包括@Configuration表示配置类,@ComponentScan进行包扫描,使用AnnotationConfigApplicationContext创建容器,@Bean创建Bean对象,@Import导入其他配置类,以及@PropertySource读取属性文件。
摘要由CSDN通过智能技术生成

Spring使用注解代替配置文件

@Configuration

在之前我们使用Spring都需要创建配置文件,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="spring.ioc.stu"/>

    <bean id="book" class="spring.ioc.stu.bean.Book">
    </bean>
</beans>

但是频繁创建xml文件非常繁琐,也会导致项目结构复杂,不利于后续开发维护。Spring为开发人员提供了一个注解@Configuration用来解决上述问题,下面来看演示类:

@Configuration
public class SpringConfiguration {
   

}

在一个类上添加@Configuration注解表示SpringConfiguration类是一个配置类,等同于只有文件头的xml文件。

@CompantScan

只有一个空的xml文件还不够,我们经常用到context:component-scan为我们的项目配置包扫描路径。Spring中提供了@ComponentScan注解来完成包扫描功能。

@Configuration
@ComponentScan("spring.ioc.stu")
public class SpringConfiguration {
   

}
AnnotationConfigApplicationContext

我们使用上面的两个注解代替了配置文件,而之前所使用的ClassPathXmlApplicationContext创建容器的方式就不可用了,创建容器的方式也应该随之改变。

public class IOCTest {
   
    @Test
    public void test() {
   
        Application
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值