ApplicationContext
这个工厂主要用于对象创建。
applicationContext
可以看出 applicationContext
继承了下面 4
个接口
MessageSource
ResourcePatternResolver
ApplicationEventPublisher
EnvironmentCapable
MessageSource 国际化服务
在 src/main/resource
中,创建一个 application.yaml
文件内容如下
1 2 3 4
| spring: messages: basename: g11n/message encoding: UTF-8
|
这是告诉翻译文件在哪里。在 src/main/resource
创建 g11n
文件夹,然后创建两个文件,目录结构如下
1 2 3 4 5 6
| -src/main/resource - application.yaml - g11n - message.properties - message_en.properties - message_zh.properties
|
在 message_zh.properties
加上 hi = 你好
然后 run
下面的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| package com.lou.springboot;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext;
import java.util.Locale;
@SpringBootApplication public class Application {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException { ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(Application.class, args);
System.out.println(configurableApplicationContext.getMessage("hi", null, Locale.CHINA)); } }
|
输出正常。
获取资源文件
1 2 3 4 5 6 7 8 9 10 11 12
| @SpringBootApplication public class Application {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, IOException { ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(Application.class, args);
Resource[] resources = configurableApplicationContext.getResources("classpath:application.properties"); for (Resource resource : resources) { System.out.println(resource); } } }
|
获取环境变量
1 2 3 4 5 6 7 8 9 10
| @SpringBootApplication public class Application {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, IOException { ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(Application.class, args);
System.out.println(configurableApplicationContext.getEnvironment().getProperty("java_home")); System.out.println(configurableApplicationContext.getEnvironment().getProperty("spring.datasource.username")); } }
|
发送事件