• SpringBoot XML和JavaConfig


    0 前言

    0.1 为什么需要使用SprintBoot

    spring和SpringMVC需要使用大量的配置文件。需要配置各种对象,把对象放到spring容器中才能使用对象。

    SpringBoot相当于不需要配置文件的Spring和SpringMVC。常用的框架和第三方库都已经配置好了,可以直接使用。提高了开发效率。

    1 JavaConfig

    JavaConfig是Spring提供的使用java类配置容器。配置Spring IOC容器的纯java方法。
    【优点】
    (1) 可以使用面向对象方式,一个配置类可以继承配置类,可以重写方法
    (2) 避免了繁琐的xml配置。

    1.1 注解

    @Configuration: 放在类上面,表示这个类可以作为配置文件使用。
    @Bean:声明对象,把对象注入到容器中。此注解,如果不指定兑现的名称,默认方法名称就是id。使用name属性指定bean的id

    @Configuration
    public class SprintConfig {
        /**
         *  方法返回值的对象就直接被注入到容器中了。
         */
    	@Bean
    	public Student createStudent() {
    		Student student = new Student();
    		student.setName();
    		student.setAge();
    		student.setSex();
    		return student;
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    2 @ImportResource

    注解的作用是导入其他的xml配置文件。等同于xml文件的resources标签

    <import resources = "其他配置文件">
    
    • 1
    @Configuration
    @ImportResource(value = "classpath:applicationContext.xml")
    public class SprintConfig {
    }
    
    • 1
    • 2
    • 3
    • 4

    3 @PropertyResource

    读取properties属性配置文件,使用属性配置文件可以实现外部化配置,在程序之外提供数据。

    tiger.name= dongbeihu
    tiger.age=12
    
    • 1
    • 2
    @Component("tiger")
    public class Tiger {
    	@Value(${tiger.name})
    	private String name;
    	@Value(${tiger.age})
    	private int age;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    @Configuration
    @ImportResource(value = "classpath:applicationContext.xml")
    @PropertySource(value = "classpath:config.properties")
    @ComponentScan(basePackages = "com.xxx.vo")
    public class SprintConfig {
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  • 相关阅读:
    Qt/C++音视频开发69-保存监控pcm音频数据到mp4文件/监控录像/录像存储和回放/264/265/aac/pcm等
    No spring.config.import property has been defined
    Go 支持 OOP: 用 struct 代替 class
    数字世界的艺术家_1024特别纪念篇
    【LeetCode每日一题】——70.爬楼梯
    vue中计算属性computed的特性和应用
    手把手教你Linux磁盘分区与文件挂载
    FastAPI学习-22.response 异常处理 HTTPException
    Centos7 安装 Docker
    安全技术和防火墙
  • 原文地址:https://blog.csdn.net/kaikai_sk/article/details/126409423