springboot学习笔记(六)

@ImportResource注解

    作用:

           spring boot会 默认的 自动的 将spring等的配置文件配置好。

           但是如果要自己编写spring等配置文件,spring boot默认不能识别。

           如果需要识别,则需要在springboot主配置类上使用该注解指定配置文件的路径。(但是不推荐手写配置文件)

示例:

手动编写spring配置文件,并配置一个bean

测试能不能获取到:会提示没有这个bean

但是在主配置类加上@ImportResource注解之后,继续测试

测试方法:

获取成功

 

推荐的配置方式:xml配置文件,通过注解配置

           springboot推荐使用注解方式(配置类的方式)进行配置:

                @Configuration  :声明这是一个配置类

                @Bean:配置一个bean就加一个@Bean

示例:(这个小示例不知道为什么有一个小bug,等调试成功之后再更新)

首先编写一个配置类

package com.example.conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.example.service.StudentService;

@Configuration//声明该类是一个配置类
public class StudentConf {
	@Bean//配置一个bean
	public StudentService stuService2() {
		StudentService studentService = new StudentService();
		return studentService;
	}
}

springboot全局配置文件中的占位符、表达式

随机占位符:

${random.uuid} uuid
${random.int} 随机整数
${random.value} 随机字符串
${random.long} 随机长整形数
${random.int(10)} 10以内整数
${random.int[1024,65536]} 指定随机数范围

使用方式------直接在默认配置文件中使用即可 :

测试:

引用变量值

两个默认的配置文件之间可以相互引用

例如:在application.properties中可以引用application.yml中的值

示例:

application.properties文件:

 application.yml文件中引用application.properties的值:

 

猜你喜欢

转载自blog.csdn.net/dongjinkun/article/details/82952895