码迷,mamicode.com
首页 > 移动开发 > 详细

WebServerInitializedEvent &ApplicationRunner

时间:2019-10-19 20:55:02      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:getname   oid   对象   amp   org   sys   info   ret   jvm   

application.properties

app.name=yaoyuan2
app.dept.id=1

MyConfig.java

import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfig {
    @Value("${app.name}")
    public String name;
    @Value("${app.dept.id}")
    public String id;

    @Bean
    public Dept getDept() {
        return new Dept(id);
    }
    @Bean
    public User getUser() {
        return new User(name,getDept());
    }
}
@Data
@AllArgsConstructor
class User {
    private String name;
    private Dept dept;
}
@Data
@AllArgsConstructor
class Dept {
    private String id;
}

 

初始化:

@EventListener(WebServerInitializedEvent.class)
public void onWebServerReady(WebServerInitializedEvent event) {
    System.out.println("1.当前WebServer实现类为:"+event.getWebServer().getClass().getName());
    Object obj = event.getApplicationContext().getBean(User.class);
    System.out.println("获取user对象:"+obj);
}
/**
 * 在spring boot应用启动后回调
 * @param context
 * @return
 */
@Bean
public ApplicationRunner runner(WebServerApplicationContext context) {
    return args -> {
        System.out.println("2.当前WebServer实现类为:"+context.getWebServer().getClass().getName());
        Object obj = context.getBean(User.class);
        System.out.println("获取user对象:"+obj);
    };
}

输出:

2019-10-19 19:33:11.130  INFO 2312 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8080
1.当前WebServer实现类为:org.springframework.boot.web.embedded.netty.NettyWebServer
获取user对象:User(name=yaoyuan2, dept=Dept(id=1))
2019-10-19 19:33:11.135  INFO 2312 --- [           main] c.e.s.App                                : Started App in 4.57 seconds (JVM running for 5.33)
2.当前WebServer实现类为:org.springframework.boot.web.embedded.netty.NettyWebServer
获取user对象:User(name=yaoyuan2, dept=Dept(id=1))

 

WebServerInitializedEvent &ApplicationRunner

标签:getname   oid   对象   amp   org   sys   info   ret   jvm   

原文地址:https://www.cnblogs.com/yaoyuan2/p/11704943.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!