用spring的InitializingBean的afterPropertiesSet初始化

 

实例

 

@Component
public class NettyServer implements InitializingBean{
	@Resource
	private ChannelInitializer<SocketChannel> childHandler;
	@Value("${netty.host}")
	private String host;
	@Value("${netty.port}")
	private int port;
	public void afterPropertiesSet() throws Exception {
		System.out.println("server afterPropertiesSet");
		EventLoopGroup parentGroup = new NioEventLoopGroup(Runtime.getRuntime()
	            .availableProcessors() * 2);
		EventLoopGroup childGroup = new NioEventLoopGroup(Runtime.getRuntime()
	            .availableProcessors() * 2);
		ServerBootstrap server = new ServerBootstrap();
		server.group(parentGroup, childGroup);
		server.channel(NioServerSocketChannel.class);
		server.childHandler(childHandler);
		server.bind(new InetSocketAddress(host, port)).sync();
	}
	public void setChildHandler(ChannelInitializer<SocketChannel> childHandler) {
		this.childHandler = childHandler;
	}
	public void setHost(String host) {
		this.host = host;
	}
	public void setPort(int port) {
		this.port = port;
	}
	
	
}


参考

 

 

org.springframework.beans.factory包下有一个接口是InitializingBean 只有一个方法:


/**
  * Invoked by a BeanFactory after it has set all bean properties supplied
  * (and satisfied BeanFactoryAware and ApplicationContextAware).
  * <p>This method allows the bean instance to perform initialization only
  * possible when all bean properties have been set and to throw an
  * exception in the event of misconfiguration.
  * @throws Exception in the event of misconfiguration (such
  * as failure to set an essential property) or if initialization fails.
  */
 void afterPropertiesSet() throws Exception;
 


这个方法将在所有的属性被初始化后调用。


但是会在init前调用。


但是主要的是如果是延迟加载的话,则马上执行。


所以可以在类上加上注解:


import org.springframework.context.annotation.Lazy;


@Lazy(false)


这样spring容器初始化的时候afterPropertiesSet就会被调用。

 

只需要实现InitializingBean接口就行。

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值