服务器启动时后 调用bean的某个方法

本文介绍了一种在Tomcat启动时初始化并运行Netty Socket服务器的方法。通过使用@PostConstruct注解或XML配置文件中的init-method属性,可以确保服务器在应用启动时正确启动。示例代码展示了如何配置SSL上下文并设置Netty服务器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

场景: 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" />

 

转载于:https://my.oschina.net/jamescasta/blog/831148

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值