首页 > 解决方案 > 通过 Spring Boot 加载要映射的属性文件

问题描述

所以我正在尝试学习 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;
    }

    }

小服务程序类:

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 类设为空。

这是日志的一部分:

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

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

标签: javaspringspring-boot

解决方案


您需要@Component在 DemoProperty 类上添加注释。目前在应用程序启动期间它不被视为 bean。


推荐阅读