场景: tomcat 启动时候 需要调用一个bean的某个方法
举例: tomcat 启动 调用start方法
public final class NettySocketServer {
static final boolean SSL = System.getProperty("ssl") != null;
static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8090"));
// @PostConstruct
public void start() throws CertificateException, SSLException, InterruptedException {
new Thread(){
@Override
public void run() {
// Configure SSL.
SslContext sslCtx = null;
if (SSL) {
SelfSignedCertificate ssc = null;
try {
ssc = new SelfSignedCertificate();
} catch (CertificateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
} catch (SSLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
sslCtx = null;
}
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new WebSocketChildChannelHandler(sslCtx));
Channel ch = b.bind(PORT).sync().channel();
System.out.println("Open your web browser and navigate to " +
(SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/');
try {
ch.closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("2222222222222222");
} catch (InterruptedException e1) {
e1.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}.start();;
}
}
处理方方法:
1 通过注解
在 NettySocketServer 上用注解@service
在start方法上用注解 @PopstConstruct
2 通过XML配置
<bean id="XXX" class="xxx.NettySocketServer" init-method="start" />