0

I have two primary doubts about spring:

  1. When we get a bean from context, should we must use ways like :

    context = new ClassPathXmlApplicationContext("applicationContext.xml");

    Should it be called only via this explicit way? I was thinking about that when the website start, this spring config file should also be read.

  2. When we use tags of spring or other packages like jstl, etc. We should give the reference statement first like :

    <%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>

    I was so curious about that, when the page is parsing, the web server do download this uri and use it in this page? But without internet, it seems also work. How it works, or why we must add this in the head part of a file.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

1
  1. It is indeed possible to get a bean from the Spring context that way, but it might be considered to be defeating the purpose of having a bean container with dependency injection. The goal of the container would be to provide the beans to your classes, so they don't need to instantiate or grab them directly from the context. See this short tutorial for a simple example of (xml-based) DI.

  2. The uri attribute in a <%taglib> tag can be resolved locally if the tld is in your classpath under a certain specific path. See With JSP, does the taglib URI mean that my site is reliant on the URI resolving?.

Community
  • 1
  • 1
Xavi López
  • 27,550
  • 11
  • 97
  • 161
  • HI, Xavi López. About the first Q. How can I get a bean in my java codes? – Little Bird Oct 29 '14 at 07:20
  • now I know. We can use ApplicationContextAware to get the context by override its setter: @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if(applicationContext==null) { this.applicationContext =applicationContext; } } and config this class as a bean in applicationContext.xml like: But I still have a question about how it works. When the web start and spring context is read, who will call this setter function? (I inject nothing into this bean in the xml) – Little Bird Oct 29 '14 at 08:20