zoukankan      html  css  js  c++  java
  • spring加载配置新旧方式对比

    老方式

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

    新旧方式对比

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

  • 相关阅读:
    C# 获取类似java gettime() 的时间格式
    LUbuntu电脑棒安装指南
    Visual Studio Gallery
    SQL SERVER 分页存储过程
    asp.mvc获取checkbox、radio、select的值
    C#面向对象的一些笔记
    Javascript预解析、作用域、作用域链
    解决ajax请求cors跨域问题
    Asp.Net操作WebServices
    2019年科技趋势前10位
  • 原文地址:https://www.cnblogs.com/meituan/p/10614160.html
Copyright © 2011-2022 走看看