您的位置:首页 > 编程语言 > Java开发

反射注入失败的原因!

2015-09-23 10:19 447 查看
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">因为前一段时时间公司没有什么新项目,个人闲着无聊就写自己人生中第一个框架(方便自己以后偷懒...)。可能是自己的技术还是不够吧,这期间遇到很多问题,而且网上基本找不到这种问题的答案,这也是我写这篇博文的原因。</span>

下面来讲一下我在其中遇到主要的问题,注入失败(主要是对spring不熟悉造成的)

框架是通过配置文减里指定的类里面指定的方法去对页面静态化处理  

<ftl-factory>
<ftl id="news"  impl="com.kun.ftl.News">
<template id="news.student"  template="template/news.ftl"   savePath="html/student_news.shtml"/>
<template id="news.teacher"  template="template/news.ftl"   savePath="html/teacher_news.shtml"/>
<template id="news.art"  template="template/news.ftl"   savePath="html/art/"/>
</ftl>
<ftl id="test"  impl="com.kun.ftl.Test">
<template id="test.student"  template="template/news.ftl"   savePath="html/student_test.shtml"/>
<template id="test.teacher"  template="template/news.ftl"   savePath="html/teacher_test.shtml"/>
</ftl>

</ftl-factory>
</root>


比如上面的  指定类: com.kun.ftl.News    指定的方法:news.art    指定模板:template   生成的文件存放于/html/ate/下      下面贴上News类

package com.kun.ftl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;

import com.kun.DTO.NewsDTO;
import com.kun.sevice.NewsService;
import com.kun.template.statics.FtlBase;
@Named("news")
public class News extends FtlBase {
@Inject
private NewsService ns;

public Map student(Object arg){
Map root = new HashMap();
root.put("user","王二小");
return root;
}

public Map teacher(Object arg){
Map root = new HashMap();
for (int i = 0; i < 5; i++) {
root.put(""+i,new HashMap());
}
root.put("user","王王小二");
return root;
}
public Map art(Object arg){
Map<String,Map> root = new HashMap<String,Map>();
List<NewsDTO> list = ns.findNews();
for (int i =0 ;i<list.size() ;i++) {
Map map =new HashMap<>();
map.put("news", list.get(i));
root.put("news"+i, map);
}
return root;
}
public NewsService getNs() {
return ns;
}
public void setNs(NewsService ns) {
this.ns = ns;
}

}


大家可以看到news中的art方法   这时候友们多同学就认为:啊我知道了, 直接利用反射对com.kun.ftl.News实例化不就可以调用art了吗?

然而事实很残酷,(鄙人当初也是这么做的),这样可是会用大大的空指针异常。为什么呢?

原因是  我们用反射机制实例化出来的对象并不是 spring容器里管理的bean,因此我们的News对象里的 ns对象是null,

要解决这个 很简单  要不你把ns对象弄出来(不可取,后面还有个dao与数据库相连呢,你有种就试试这种方法),要不你就在spring容器里取出你要的 ns 或者 News 对象。

取出spring容积里的bean  不能只要继承实现一下 ApplicationContextAware 这位先生就行了。

今天说这个 1 是想给大家提供一下这类问题的决绝方法, 2这里面可以学到spring框架的一些架构知识。

希望这个能帮助到大家(这个是半年前写的,有很多东西已经忘了,里面有哪里讲错的,或者不好的,希望大家多谅解一下,我才毕业一年而已...)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息