RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1125979
Accepted
Miron
Miron
Asked:2020-05-15 18:06:18 +0000 UTC2020-05-15 18:06:18 +0000 UTC 2020-05-15 18:06:18 +0000 UTC

无法从spring xml上下文中的属性文件中获取属性getEnvironment

  • 772

文件内容people.properties:

knight.age=34  
knight.name=Pedro

文件内容annotationsBased.xml:

<context:property-placeholder location="classpath:people.properties"/>
<bean class="ru.miron.SOWithDocs.Entities.Person" id="knightCreatedUsingPropertiesFile">
    <constructor-arg name="age" value="${knight.age}"/>
    <constructor-arg name="name" value="${knight.name}"/>
</bean>

收到后:

ApplicationContext XMLcontext = new ClassPathXmlApplicationContext("annotationsBased.xml");
System.out.println("Knight created using properties file - " + XMLcontext.getBean("knightCreatedUsingPropertiesFile"));

输出如下:

Knight created using properties file - Person [age=34, name=Pedro]

这意味着文件中的属性已成功加载到SpEL.


为什么在下一步执行以下代码时:

System.out.println(XMLcontext.getEnvironment().getProperty("knight.age"));

结论—— null?

java
  • 2 2 个回答
  • 10 Views

2 个回答

  • Voted
  1. Best Answer
    Miron
    2020-05-24T17:40:45Z2020-05-24T17:40:45Z

    有两种接口方法Environment可以使用以下方法获取此类属性SpEL:

    .resolveRequiredPlaceholders(文本);
    .resolvePlaceholders(文本);

    它们略有不同。

    .resolveRequiredPlaceholders(text):

    抛出: IllegalArgumentException - 如果给定文本为 null 或任何占位符无法解析

    resolvePlaceholders(text):

    抛出: IllegalArgumentException - 如果给定文本为空

    执行以下代码行时:

    System.out.println(context.getEnvironment().resolvePlaceholders("${knight.age}"));
    System.out.println(context.getEnvironment().resolvePlaceholders("${knight.name}"));
    

    我们得到输出:

    34
    佩德罗

    这是最简单的让。您还可以使用注释检查这一点@PropertySource:

    @Component
    @PropertySource("classpath:people.properties") // can include many .properties files
    public class EnvironmentFabric {
        @Autowired
        public Environment en;
    
        @Value("${knight.name}")
        public String knightName;
        @Value("${knight.age}")
        public int knightAge;
    
        public Environment getEnvironment() {
            return en;
        }
    
        public void printKnight() {
            System.out.println("knight name: " + knightName + ", knight age: " + knightAge);
        }
    }
    

    并且在执行以下代码时:

    EnvironmentFabric enF = context.getBean("environmentFabric", EnvironmentFabric.class);
    System.out.println(enF.getEnvironment().getProperty("knight.name"));
    System.out.println(enF.getEnvironment().getProperty("knight.age"));
    enF.printKnight();
    

    输出将是:

    佩德罗
    34
    骑士姓名:佩德罗,骑士年龄:34

    答案基于这篇文章。
    文章对题目进行了更详细的分析。

    • 0
  2. user328896
    2020-05-24T20:59:13Z2020-05-24T20:59:13Z

    该文件properties连接到spring配置类中的上下文并写入 bean Environment。请参阅Spring 和 Spring Boot 的属性。然后可以将这个 bin 注入到任何其他 bin 中。

    例如,在同一个地方,在配置类中:

    @Bean(name = "knight1")
    public Person knight(Environment environment) {
        Person knight1 = new Person();
        knight1.setAge(environment.getProperty("knight.age"));
        knight1.setName(environment.getProperty("knight.name"));
        return knight1;
    }
    

    或者在控制器类的构造函数中:

    @Autowired
    public Controller(Environment environment) {
        Person knight2 = new Person();
        knight2.setAge(environment.getProperty("knight.age"));
        knight2.setName(environment.getProperty("knight.name"));
    
        this.knight2 = knight2;
    }
    

    如果有很多带有属性的文件,那么在连接每个文件时,我们为其指定一个名称:

    @PropertySource(name = "knight1.properties", value = "classpath:resources/knight1.properties", encoding = "UTF-8")
    @PropertySource(name = "knight2.properties", value = "classpath:resources/knight2.properties", encoding = "UTF-8")
    

    添加豆propertySources:

    @Bean
    public PropertySources propertySources(ConfigurableEnvironment environment) {
        return environment.getPropertySources();
    }
    

    然后我们从这个bean中获取属性:

    @Bean(name = "knight1")
    public Person knight(@Value("#{propertySources.get('knight1.properties')}")
                                     ResourcePropertySource propertySource) {
        Person knight1 = new Person();
        knight1.setAge(propertySource.getProperty("knight.age"));
        knight1.setName(propertySource.getProperty("knight.name"));
        return knight1;
    }
    

    示例:骑士项目

    项目结构:

    knights-project
    ├── src
    │   └── main
    │       ├── java
    │       │   └── knights
    │       │       ├── Controller.java
    │       │       ├── Person.java
    │       │       └── WebAppConfig.java
    │       └── resources
    │           ├── knight1.properties
    │           └── knight2.properties
    └── pom.xml
    

    控制器.java

    @RestController
    public class Controller {
        private final HashMap<String, Person> band;
    
        @Autowired
        public Controller(@Qualifier("knight1") Person knight1,
                          @Value("#{propertySources.get('knight2.properties')}")
                                  ResourcePropertySource propertySource) {
    
            Person knight2 = new Person();
            knight2.setAge(propertySource.getProperty("knight.age"));
            knight2.setName(propertySource.getProperty("knight.name"));
    
            this.band = new HashMap<>();
            this.band.put("knight1", knight1);
            this.band.put("knight2", knight2);
        }
    
        @RequestMapping(value = {"/", "/index.html"})
        public ResponseEntity<?> mainPage() {
            return ResponseEntity.ok(band);
        }
    }
    

    客户端: index.html

    {
      "knight2": {
        "age": 35,
        "name": "González"
      },
      "knight1": {
        "age": 34,
        "name": "Pedro"
      }
    }
    

    人.java

    public class Person {
        private int age;
        private String name;
    
        public Person() {
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(Object age) {
            this.age = Integer.parseInt(String.valueOf(age));
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(Object name) {
            this.name = String.valueOf(name);
        }
    }
    

    WebAppConfig.java

    @Configuration
    @ComponentScan
    @EnableWebMvc
    @PropertySource(name = "knight1.properties", value = "classpath:resources/knight1.properties", encoding = "UTF-8")
    @PropertySource(name = "knight2.properties", value = "classpath:resources/knight2.properties", encoding = "UTF-8")
    public class WebAppConfig implements WebApplicationInitializer {
        @Override
        public void onStartup(ServletContext servletContext) {
            CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
            encodingFilter.setEncoding("UTF-8");
            encodingFilter.setForceEncoding(true);
    
            servletContext
                    .addFilter("encoding-filter", encodingFilter)
                    .addMappingForUrlPatterns(null, false, "/*");
    
            AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
            applicationContext.register(WebAppConfig.class);
            applicationContext.setServletContext(servletContext);
    
            ServletRegistration.Dynamic servlet =
                    servletContext.addServlet("dispatcher", new DispatcherServlet(applicationContext));
    
            servlet.setLoadOnStartup(1);
            servlet.addMapping("/");
        }
    
        @Bean
        public PropertySources propertySources(ConfigurableEnvironment environment) {
            return environment.getPropertySources();
        }
    
        @Bean(name = "knight1")
        public Person knight(@Value("#{propertySources.get('knight1.properties')}")
                                         ResourcePropertySource propertySource) {
            Person knight1 = new Person();
            knight1.setAge(propertySource.getProperty("knight.age"));
            knight1.setName(propertySource.getProperty("knight.name"));
            return knight1;
        }
    }
    

    骑士1.properties

    knight.age=34
    knight.name=Pedro
    

    骑士2.properties

    knight.age=35
    knight.name=González
    

    pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
              http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>knights-project</groupId>
        <artifactId>knights-project</artifactId>
        <name>knights-project</name>
        <version>1.0.0</version>
        <packaging>war</packaging>
    
        <properties>
            <java.version>14</java.version>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        </properties>
    
        <build>
            <defaultGoal>package</defaultGoal>
            <resources>
                <resource>
                    <directory>src/main/resources</directory>
                    <targetPath>resources</targetPath>
                </resource>
            </resources>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.1</version>
                    <configuration>
                        <source>${java.version}</source>
                        <target>${java.version}</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.3</version>
                </plugin>
            </plugins>
        </build>
    
        <dependencies>
            <!-- spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.2.6.RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.11.0</version>
            </dependency>
    
            <!-- common -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>4.0.1</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>
    </project>
    
    • 0

相关问题

  • wpcap 找不到指定的模块

  • 如何以编程方式从桌面应用程序打开 HTML 页面?

  • Android Studio 中的 R.java 文件在哪里?

  • HashMap 初始化

  • 如何使用 lambda 表达式通过增加与原点的距离来对点进行排序?

  • 最大化窗口时如何调整元素大小?

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    如何从列表中打印最大元素(str 类型)的长度?

    • 2 个回答
  • Marko Smith

    如何在 PyQT5 中清除 QFrame 的内容

    • 1 个回答
  • Marko Smith

    如何将具有特定字符的字符串拆分为两个不同的列表?

    • 2 个回答
  • Marko Smith

    导航栏活动元素

    • 1 个回答
  • Marko Smith

    是否可以将文本放入数组中?[关闭]

    • 1 个回答
  • Marko Smith

    如何一次用多个分隔符拆分字符串?

    • 1 个回答
  • Marko Smith

    如何通过 ClassPath 创建 InputStream?

    • 2 个回答
  • Marko Smith

    在一个查询中连接多个表

    • 1 个回答
  • Marko Smith

    对列表列表中的所有值求和

    • 3 个回答
  • Marko Smith

    如何对齐 string.Format 中的列?

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5