【问题标题】:Loading Property file to map via spring boot通过 Spring Boot 加载要映射的属性文件
【发布时间】:2020-03-27 15:36:53
【问题描述】:

所以我正在尝试学习 Spring Boot,但我完全被困在这里。我正在尝试学习如何加载属性文件并通过 servlet 简单地打印结果。

这是我的application.properties 文件

example.mapProperty.key1=MapValue1
example.mapProperty.key2=MapValue2

属性类:

import org.springframework.boot.context.properties.ConfigurationProperties;

@PropertySource("classpath:application.properties")
@ConfigurationProperties(prefix = "example")
public class DemoProperty {

    private Map<String, String> mapProperty;

    public Map<String, String> getMapProperty() {
        return mapProperty;
    }

    public void setMapProperty(Map<String, String> mapProperty) {
        this.mapProperty = mapProperty;
    }

    }

Servlet 类:

public class HelloCountryServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final Logger logger = LogManager.getLogger(HelloCountryServlet.class);

    @Autowired
    private DemoProperty demoProperty;

    public void setDemoProperty(DemoProperty demoProperty) {
            this.demoProperty = demoProperty;
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doGet(request, response);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        logger.info("Logger is running");
        logger.info("demoProperty :: " + demoProperty);
        PrintWriter out = response.getWriter();
        for(Entry<String, String> i : demoProperty.getMapProperty().entrySet()) {
                out.println("<h3>Property " + i.getKey() + " : " + i.getValue() + "</h3>");
        }
    }
}

入门类:

@SpringBootApplication
public class SpringBootAppStarter extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringBootAppStarter.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringBootAppStarter.class, args);
    }
}

pom.xml:

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath />
    </parent>

    <groupId>com.test</groupId>
    <artifactId>SpringBootApp</artifactId>
    <version>0.0.1</version>
    <packaging>war</packaging>

    <name>SpringBootApp Maven Webapp</name>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <finalName>SpringBootApp</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

我在 sts 的 Wildfly 服务器上运行它。

战争结构:

META-INF
WEB-INF __
          |
          |_ lib
          |_ classes__
                      |
                      |_ application.properties
                      |_ class files

不幸的是,我总是将 demoProperty 类设为 null。

这是日志的一部分:

0:34:15,484 INFO  [stdout] (default task-1) 2020-03-27 20:34:15.484 [INFO ] DispatcherServlet 547 - Completed initialization in 12 ms

20:34:22,454 INFO  [stdout] (default task-1) 2020-03-27 20:34:22.453 [INFO ] HelloCountryServlet 35 - Logger is running

20:34:22,454 INFO  [stdout] (default task-1) 2020-03-27 20:34:22.454 [INFO ] HelloCountryServlet 36 - demoProperty :: null

20:34:22,464 INFO  [stdout] (default task-1) 2020-03-27 20:34:22.458 [ERROR] ErrorPageFilter 183 - Forwarding to error page from request [/country] due to exception [null]

20:34:22,464 INFO  [stdout] (default task-1) java.lang.NullPointerException: null

20:34:22,464 INFO  [stdout] (default task-1)    at com.test.servlets.HelloCountryServlet.doGet(HelloCountryServlet.java:38) ~[classes:?]

20:34:22,464 INFO  [stdout] (default task-1)    at javax.servlet.http.HttpServlet.service(HttpServlet.java:503) ~[jboss-servlet-api_4.0_spec-2.0.0.Final.jar!/:2.0.0.Final]

我一直使用这些链接作为参考: https://mkyong.com/spring-boot/spring-boot-configurationproperties-example/

http://www.jcombat.com/spring/how-to-read-properties-using-spring-boot-configurationproperties

有人能帮我一下吗。提前致谢。

【问题讨论】:

  • 您的 servlet 类似乎没有使用 Service/Component/Bean 进行注释。
  • @AhmetOZKESEK - 查看上面的日志,可以确定 servlet 类正在执行。我认为 Servlet 类没有任何问题。
  • @dhana1310 - 非常正确。 servlet 没有问题
  • HelloCountryServlet 不是 Spring 托管 bean,因此没有发生依赖注入。用 @Controller 注释类,提供正确的 http 方法映射并重试。您没有使用 Spring MVC,这是 NPE 的原因
  • @Component注释你的DemoProperty

标签: java spring spring-boot


【解决方案1】:

您需要在您的 DemoProperty 类上添加 @Component 注释。目前在应用启动时不被视为 bean。

【讨论】:

  • 抱歉延迟回复。我们停电了。我已经试过了,但没有用。
  • 我可以问一个问题吗?是否必须在 @RestController 类中自动装配 DemoProperty 类?
  • 参考链接都是这样建议的
  • @Aron spring 依赖注入有 3 种方式,1.Field 级别(你正在使用这个),2. Constructor 级别和 3. Setter 级别。字段级别不是首选方式。
猜你喜欢
  • 2021-09-23
  • 2019-03-30
  • 2017-11-17
  • 2016-01-30
  • 2020-07-25
  • 2014-12-21
  • 2012-10-01
  • 2019-02-12
  • 2020-04-14
相关资源
最近更新 更多