spring加载配置新旧方式对比

时间:2023-03-08 17:02:23

老方式

1、首先要配置配置文件,如beans.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="person" class="com.enjoy.cap1.Person">
<property name="name" value="james"></property>
<property name="age" value="19"></property>
</bean>
</beans>

2、读取配置文件,并初始化,代码如下:

//把beans.xml的类加载到容器
ApplicationContext app = new ClassPathXmlApplicationContext("beans.xml");
//从容器中获取bean
Person person = (Person) app.getBean("person"); System.out.println(person);

新方式

1、声明一个配置类

//配置类====配置文件
@Configuration
public class MainConfig {
//给容器中注册一个bean, 类型为返回值的类型,
@Bean("person")
public Person person01(){
return new Person("james",20);
}
}

2、读取配置类,初始化

ApplicationContext app = new AnnotationConfigApplicationContext(MainConfig.class);

//从容器中获取bean
Person person = (Person) app.getBean("person"); System.out.println(person);

新旧方式对比

当老方式要初始化配置很多的时候,要写很多个配置文件,不利于项目维护,推荐用新方式加载配置