3.实现注入
3.1构建applicationContext.xml
在src目录下建立applicationContext.xml
< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
3.1构建注入开始点
在HttpServer.java里加入
private BeanFactory beanFactory;
public HttpServer() {
ClassPathResource classPathResource = new ClassPathResource(
"applicationContext.xml");
beanFactory = new XmlBeanFactory(classPathResource);
}
public Object getBean(String beenName){
return beanFactory.getBean(beenName);
}
3.2注入HttpServerPipelineFactory
在applicationContext.xml里加入
修改HttpServer.java的main函数
public static void main(String[] args) {
// Configure the server.
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
HttpServer httpServer = new HttpServer();
/ 提取httpServerPipelineFactory
HttpServerPipelineFactory httpServerPipelineFactory=(HttpServerPipelineFactory)httpServer.getBean("httpServerPipelineFactory");
// Set up the event pipeline factory.
// Bind and start to accept incoming connections.
bootstrap.bind(new InetSocketAddress(8081));
}
3.3HttpServerPipelineFactory注入HttpRequestHandler
把applicationContext.xml里beans内容改为
修改HttpServerPipelineFactory.java的main函数
public class HttpServerPipelineFactory implements ChannelPipelineFactory {
private HttpRequestHandler httpRequestHandler;
public void setHttpRequestHandler(HttpRequestHandler httpRequestHandler) {
this.httpRequestHandler = httpRequestHandler;
}
public HttpRequestHandler getHttpRequestHandler() {
return httpRequestHandler;
}
public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
ChannelPipeline pipeline = pipeline();
// Uncomment the following line if you want HTTPS
// SSLEngine engine =
// SecureChatSslContextFactory.getServerContext().createSSLEngine();
// engine.setUseClientMode(false);
// pipeline.addLast("ssl", new SslHandler(engine));
pipeline.addLast("decoder", new HttpRequestDecoder());
// Uncomment the following line if you don't want to handle HttpChunks.
// pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
pipeline.addLast("encoder", new HttpResponseEncoder());
// Remove the following line if you don't want automatic content
// compression.
pipeline.addLast("deflater", new HttpContentCompressor());
pipeline.addL