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");
}
}