2016-06-11 16 views
0

我的項目是Spring-boot(1.3.5 RELEASE),Web Project(Spring-Web 4.3.0 REALESE)。 我想在彈簧加載時使用「ApplicationListener」來做某件事。但是我的代碼不工作。有我的代碼:不能使用Spring ApplicationListener

package hello;

import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent;

公共類BootListener實現ApplicationListener {

@Override 
public void onApplicationEvent(ContextRefreshedEvent event) { 
    System.out.println("Spring啓動監聽器"); 
    System.out.println(event.getTimestamp()); 

} 

}

包你好;

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

@SpringBootApplication 公共類的應用{

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

}

http://maven.apache.org/xsd/maven-4.0.0.xsd「> 4.0.0

<groupId>org.springframework</groupId> 
<artifactId>demo</artifactId> 
<version>0.1.0</version> 

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

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

<properties> 
    <java.version>1.8</java.version> 
</properties> 


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

<repositories> 
    <repository> 
     <id>spring-releases</id> 
     <url>https://repo.spring.io/libs-release</url> 
    </repository> 
</repositories> 
<pluginRepositories> 
    <pluginRepository> 
     <id>spring-releases</id> 
     <url>https://repo.spring.io/libs-release</url> 
    </pluginRepository> 
</pluginRepositories> 

+0

如果你想使用一個偵聽器,那麼你應該將它添加到彈簧的某個地方,以確認它在Spring啓動應用程序啓動時的存在。 –

+0

對,我將它註釋爲春豆。 – TungFung

回答

1

你需要ŧ o讓你的事件監聽器成爲一個單身人士,Spring可以挑選它。用@Component註釋您的BootListener

要自己發佈事件,請注入ApplicationEventPublisher

+0

正確!我只是註解了註釋。 – TungFung

相關問題