WebServerInitializedEvent &ApplicationRunner

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

上一篇:@SpringBootApplication-exclude和扫描并装配其他包下的bean(@AliasFor)


下一篇:android6.0 SystemUi分析