简体   繁体   English

spring boot - @PostConstruct 未在@Component 上调用

[英]spring boot - @PostConstruct not called on @Component

I am new to spring, and I have created a new spring boot project using https://start.spring.io/ with no further dependencies, unzipped the zip file and opened the project in IntelliJ IDEA.我是 spring 的新手,我使用https://start.spring.io/创建了一个新的 spring boot 项目,没有进一步的依赖,解压 zip 文件并在 IntelliJ IDEA 中打开该项目。 I have not done any further configurations.我没有做任何进一步的配置。 I am now trying to setup a bean with a @PostConstruct method - however, the method is never invoked by spring.我现在正在尝试使用 @PostConstruct 方法设置 bean - 但是,spring 永远不会调用该方法。

These are my classes:这些是我的课程:

SpringTestApplication.java SpringTestApplication.java

package com.habichty.test.testspring;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
    public class SpringTestApplication {

        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(SpringTestApplication.class, args);
            context.getBean(TestBean.class).testMethod();
        }
    }

TestBean.java测试Bean.java

package com.habichty.test.testspring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

@Component  
    public class TestBean {
            private final Logger log = LoggerFactory.getLogger(this.getClass());
            private int a = 1;

            public TestBean()
            {
                log.debug("Constructor of TestBean called.");
            }

            @PostConstruct
            public void init()
            {
                log.debug("init()-Method of TestBean called.");
                a = 2;
            }

            public void testMethod()
            {
                log.debug("Test Method of TestBean called. a=" + a);
            }

        }

When I start the application, this is my output:当我启动应用程序时,这是我的输出:

 :: Spring Boot ::        (v1.5.9.RELEASE)

2018-01-22 13:15:57.960  INFO 12035 --- [           main] c.h.t.testspring.SpringTestApplication   : Starting SpringTestApplication on pbtp with PID 12035 (/home/pat/prj/testspring/testspring/target/classes started by pat in /home/pat/prj/testspring/testspring)
2018-01-22 13:15:57.962 DEBUG 12035 --- [           main] c.h.t.testspring.SpringTestApplication   : Running with Spring Boot v1.5.9.RELEASE, Spring v4.3.13.RELEASE
2018-01-22 13:15:57.962  INFO 12035 --- [           main] c.h.t.testspring.SpringTestApplication   : No active profile set, falling back to default profiles: default
2018-01-22 13:15:58.018  INFO 12035 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2931522b: startup date [Mon Jan 22 13:15:58 CET 2018]; root of context hierarchy
2018-01-22 13:15:58.510 DEBUG 12035 --- [           main] com.habichty.test.testspring.TestBean    : Constructor of TestBean called.
2018-01-22 13:15:58.793  INFO 12035 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-01-22 13:15:58.822  INFO 12035 --- [           main] c.h.t.testspring.SpringTestApplication   : Started SpringTestApplication in 1.073 seconds (JVM running for 2.025)
2018-01-22 13:15:58.822 DEBUG 12035 --- [           main] com.habichty.test.testspring.TestBean    : Test Method of TestBean called. a=1
2018-01-22 13:15:58.826  INFO 12035 --- [       Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2931522b: startup date [Mon Jan 22 13:15:58 CET 2018]; root of context hierarchy
2018-01-22 13:15:58.828  INFO 12035 --- [       Thread-1] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

As you can see, spring initializes the TestBean and also executes the testMethod() - but the init()-Method, annotated with @PostConstruct, is not invoked.如您所见,spring 初始化了 TestBean 并执行了 testMethod() - 但是 init()-Method 并没有被调用,带有 @PostConstruct 注释。

What am I doing wrong?我究竟做错了什么? Any help is very appreciated.非常感谢任何帮助。

UPDATE 1 In my application.properties, I have configured:更新 1在我的 application.properties 中,我配置了:

logging.level.com = DEBUG

Changing this to logging.level.root = DEBUG results in a massively bigger log.将其更改为logging.level.root = DEBUG 会产生更大的日志。 However, it still does not contain the debug message of my init() method.但是,它仍然不包含我的 init() 方法的调试消息。

UPDATE 2 Added package and import statements.更新 2添加了 package 和 import 语句。

UPDATE 3 To further clarify that this is not a logging issue, I have added an new int to the code that should be altered by the init()-Method.更新 3为了进一步澄清这不是日志记录问题,我在应该由 init() 方法更改的代码中添加了一个新的 int。 As far as I understood the concept of the @PostConstruct annotation, it should be executed prior to any other method execution.据我了解@PostConstruct 注解的概念,它应该在任何其他方法执行之前执行。 As a consequence, the output of testMethod() should now contain a=2 .因此, testMethod() 的输出现在应该包含a=2 In the updated output, you may see that this is not the case.在更新的输出中,您可能会看到情况并非如此。

UPDATE 4 This is my POM更新 4这是我的 POM

    <?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>com.habichty.test.testspring</groupId>
    <artifactId>springTest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springTest</name>
    <description>springTest</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

The output of java -version : java -version的输出:

java version "9.0.1"
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)

Due to the new module system in Java9 SpringBoot-1.5.9 fails to process @PostConstruct as the annotation class is not on the classpath.由于 Java9 中的新模块系统SpringBoot-1.5.9无法处理@PostConstruct因为注解类不在类路径上。 The problem (or similar) is described here and here . 此处此处描述问题(或类似问题)。 There are a few ways to resolve it:有几种方法可以解决:

  • run the application with Java8,使用 Java8 运行应用程序,
    or, if still on Java9:或者,如果仍在 Java9 上:
  • add javax.annotation:javax.annotation-api dependency to the POM, orjavax.annotation:javax.annotation-api依赖添加到 POM,或
  • upgrade to a newer Spring-Boot of version 2.0.0+ (which is still PRERELEASE as of this writing) which incorporates that dependency;升级到包含该依赖项的 2.0.0+ 版本的较新 Spring-Boot(在撰写本文时仍为 PRERELEASE);

I know this Problem is already solved, but as it is the first Stackoverflow Question that came up when I googled this problem I will leave this here:我知道这个问题已经解决了,但是因为这是我在谷歌上搜索这个问题时出现的第一个 Stackoverflow 问题,所以我将把它留在这里:

I had the same issue and my error was that I had a typo in my package names.我有同样的问题,我的错误是我的包名有错别字。 My class which was calling name had a different packagename than my SpringBootApplication class.我调用 name 的类与我的 SpringBootApplication 类具有不同的包名。 So my main application was not finding my component.所以我的主要应用程序没有找到我的组件。

So always check your package names if you have a similiar problems.因此,如果您遇到类似的问题,请务必检查您的软件包名称。

I guess you did not define something like我猜你没有定义类似的东西

logging.level.root=debug

in your application.properties?在您的 application.properties 中?

Without = no logs没有 = 没有日志

With =与 =

2018-01-22 12:34:06.117 DEBUG 8516 --- [main] com.example.demo.TestBean  : Constructor of TestBean called. 
...
2018-01-22 12:34:06.117 DEBUG 8516 --- [main] com.example.demo.TestBean : init()-Method of TestBean called. 
...
2018-01-22 12:34:06.241 DEBUG 8516 --- [main]  com.example.demo.TestBean : Test Method of TestBean called.

If you are using Java 9 or higher, then you will encounter an error when using @PostConstruct and @PreDestroy in your code.如果您使用的是 Java 9 或更高版本,那么在代码中使用 @PostConstruct 和 @PreDestroy 时会遇到错误。

Eclipse is unable to import @PostConstruct or @PreDestroy Eclipse 无法导入 @PostConstruct 或 @PreDestroy

When using Java 9 and higher, javax.annotation has been removed from its default classpath.使用 Java 9 及更高版本时,javax.annotation 已从其默认类路径中删除。 That's why Eclipse can't find it.这就是 Eclipse 找不到它的原因。


Solution解决方案

  1. Download the javax.annotation-api-1.3.2.jar from下载 javax.annotation-api-1.3.2.jar 从

https://search.maven.org/remotecontent?filepath=javax/annotation/javax.annotation-api/1.3.2/javax.annotation-api-1.3.2.jar https://search.maven.org/remotecontent?filepath=javax/annotation/javax.annotation-api/1.3.2/javax.annotation-api-1.3.2.jar

  1. Copy the JAR file to the lib folder of your project将 JAR 文件复制到项目的 lib 文件夹中

Use the following steps to add it to your Java Build Path.使用以下步骤将其添加到您的 Java 构建路径。

  1. Right-click your project, select Properties右键单击您的项目,选择属性

  2. On the left-hand side, click Java Build Path在左侧,单击 Java Build Path

  3. In the top-center of dialog, click Libraries在对话框的顶部中心,单击库

  4. Click Classpath and then Click Add JARs ...单击 Classpath,然后单击 Add JARs ...

  5. Navigate to the JAR file /lib/javax.annotation-api-1.3.2.jar导航到 JAR 文件 /lib/javax.annotation-api-1.3.2.jar

  6. Click OK then click Apply and Close单击确定,然后单击应用并关闭

Eclipse will perform a rebuild of your project and it will resolve the related build errors. Eclipse 将重新构建您的项目并解决相关的构建错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM