Spring的配置文件方式

本文介绍Spring框架中的两种配置文件模式之一:使用Java代码进行配置。通过一个具体的例子展示了如何使用@Configuration和@Bean注解来定义Spring Bean,以及这种方式与XML配置的等价性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring 一般有两种配置文件模式 一种是通过XML来配置文件,另一种是通过Java代码来配置文件,如下

Java文件配置方式

package config;
import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import implement.HelloWordImplement;
import implement.HelloWordImplement2;
import minterface.HelloWord;


@Configuration
public class AppConfig {
@Bean(name = "helloBean")
public HelloWord helloWord() {
return new HelloWordImplement();
}


@Bean(name = "helloBean2")
public HelloWord helloWord2() {
return new HelloWordImplement2();
}
}

Java文件中用 @Configuration的方式告诉spring 这个类是一个配置文件,其中@Bean即时告诉spring下面的的方法需要通过setter注入的方式注入bean

其中上述配置文件等效于XML的

<bean id="helloWord" class="implement.HelloWordImplement">

</bean>

<bean id="helloWord2" class="implement.HelloWordImplement2">
</bean>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值