Загрузка файла свойств на карту с помощью весенней загрузки - PullRequest
0 голосов
/ 27 марта 2020

Итак, я пытаюсь изучить Spring Boot, и я полностью застрял здесь. Я пытаюсь узнать, как загрузить файлы свойств и просто распечатать результат через сервлет.

Это мой 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>

Я запускаю его на Wildfly сервер в sts.

Структура войны:

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

Может кто-то возражать помочь меня немного Заранее спасибо.

1 Ответ

0 голосов
/ 27 марта 2020

Вам необходимо добавить аннотацию @Component в свой класс DemoProperty. В настоящее время он не считается компонентом при запуске приложения.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...