Spring框架 Bean

STS - 开发工具
Maven - 类似cmd

工厂模式思想

XMLファイルを利用する
在xml文件中创建各种产品,在主代码中使用抽象产品获取实际产品(多态)
不需要改变java代码,只需要在xml文件中修改配置。

可以指定多个Bean,通过ID区分

	-main.java
		ApplicationContext app;

		// get an instance from xml
		// 设置配置文件是xml
		app = new ClassPathXmlApplicationContext("bean.xml");
		MybeanInterface bean2 = (MybeanInterface) app.getBean("mybean"); // 通过ID获取到需要的类
		System.out.println(bean2);

xml文件需要放在resources下

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

<bean id = "mybean" class="com.luffy.code.MyBean2">
	<property name="message" value="2131231"></property>
</bean>

</beans>

Bean構成クラスを利用する
不需要改变java主代码,只需要在java类AutoMyBeanConfig 中直接配置需要的子类

		// get an instance from class
		// 设置配置文件为AutoMyBeanConfig 类
		app = new AnnotationConfigApplicationContext(AutoMyBeanConfig.class);
		// 获取到bean
		MybeanInterface bean3 = app.getBean(MybeanInterface.class);
		System.out.println(bean3);
package com.luffy.code;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;

// 一个Configurable下只能有一个Bean
@Configurable
public class AutoMyBeanConfig {

	@Bean
	public MybeanInterface myBean() {
		// set MyBean
		// 在这里创建实际产品
		return new MyBean("213132");
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值