<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框架的一些架構知識。
希望這個能幫助到大家(這個是半年前寫的,有很多東西已經忘了,裏面有哪裏講錯的,或者不好的,希望大家多諒解一下,我才畢業一年而已...)