@Configuration和@Bean

本文详细介绍了如何使用Spring框架中的注解@Configuration和@Bean替代XML配置,实现类和方法级别的配置,包括实例化第三方对象如Redis的配置过程。

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

在类上添加注解@Configuration,代替xml配置中的beans

@Configuration
public class ConfigurationDemo {
	ConfigurationDemo(){
		System.out.println("加载完成");
	}
}

在测试类加载本类

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestDemoApplicationTests {
	@Test
	public void contextLoads() {
		AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ConfigurationDemo.class);
	}
}

在方法上添加@Bean,代替xml配置中的bean  <bean id=" " class="  "> 

@Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同

/**
* 写一个类
*/
public class TestPojo {
	private Integer id;
	private String name;
	public void sayHi() {
		System.out.println("hi");
	}
}
/**
*在有@Configuration注解修饰的类中写一个被@Bean修饰的方法
*/
@Configuration
public class ConfigurationDemo {
	ConfigurationDemo(){
		System.out.println("加载完成");
	}
	
	@Scope("prototype")
	@Bean   //等价于 <bean id="testPojo" class="TestPojo">
	public TestPojo testPojo() {
		return new TestPojo();
	}
}
/**
*测试
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestDemoApplicationTests {
	@Test
	public void contextLoads() {
		AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ConfigurationDemo.class);
		TestPojo tp = (TestPojo)ac.getBean("testPojo");
		tp.sayHi();
	}
}

当需要将第三方对象交给spring容器管理时,常常需要用到@Configuration和@Bean

例子:使用第三方的Redis

@Configuration   //表示我是一个配置类
@PropertySource("classpath:/properties/redis.properties") //读取配置文件
public class RedisConfig {
	@Value("${redis.host}")  //获取配置文件中的主机号
	private String host;
	@Value("${redis.port}")  //获取配置文件中的端口号
	private int port;
	
	@Bean
	public Jedis jedis() {
		return new Jedis(host,port);//创建一个Redis对象
	}	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值