Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

怎么在非servlet或者action中获取ioc中的实例 #273

Closed
xie041 opened this issue Jul 18, 2012 · 6 comments
Closed

怎么在非servlet或者action中获取ioc中的实例 #273

xie041 opened this issue Jul 18, 2012 · 6 comments

Comments

@xie041
Copy link

xie041 commented Jul 18, 2012

Dao dao = Mvcs.getIoc().get(Dao.class, "dao");获取不到?

public class KeywordTimer implements ServletContextListener{

    private Logger log = Logger.getLogger(KeywordTimer.class);

    private Timer timer;

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        timer.cancel();
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        timer =new Timer(true);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {

                Dao dao = Mvcs.getIoc().get(Dao.class, "dao");
                System.out.println(dao == null);

            }
        },10*1000,1*15*1000);//3分钟
    }
}
@wendal
Copy link
Member

wendal commented Jul 18, 2012

Mvcs.getIoc()仅在请求范围内有效

你可以通过@SetupBy, 使用自己的Setup类, 将Ioc容器保存到自己的静态变量中

@wendal wendal closed this as completed Jul 18, 2012
@zozoh
Copy link
Member

zozoh commented Jul 18, 2012

如果你的对象是由 Ioc 容器组装的,你可以声明一个成员变量

  @Inject("refer:$Ioc")
  private Ioc ioc;

容器会把自身的引用设置给你这个变量,相关文档 http://code.google.com/p/nutz/wiki/ioc_injecting#容器自身

@xie041
Copy link
Author

xie041 commented Jul 18, 2012

"@SetupBy, 使用自己的Setup类, 将Ioc容器保存到自己的静态变量中",用这个搞法真的很绝!

@zozoh
Copy link
Member

zozoh commented Jul 18, 2012

@xie041 通过 @SetupBy 你可以做更多更绝的事情 :P

@xie041
Copy link
Author

xie041 commented Jul 19, 2012

启动的时候,自动把bean映射到数据库,这样搞合适不?
Ioc ioc = config.getIoc();
dao = ioc.get(Dao.class, "dao");
List cls = Scans.me().scanPackage("package");
for(Class<?> bean : cls){
Table table = (Table) bean.getAnnotation(Table.class);
if(table!=null){
dao.create(bean, false);
}
}

@zozoh
Copy link
Member

zozoh commented Jul 19, 2012

哦,我一般也是这么搞,不过我都是写死的。写一排 dao.create(XXXX.class, false)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants