In Spring bean you can easily access other beans. There have 3 methods to get beans in Java class.
Java Annotation:
@Autowired private MyBean bean;
<bean id="person" class="org.springframework.beans.TestBean" scope="prototype"> <property name="age" value="10"/> <property name="spouse"> <bean class="org.springframework.beans.TestBean"> <property name="age" value="11"/> </bean> </property> </bean>
or get a bean in run time:
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); Object bean = context.getBean("myBean");
In JSP, You can use the third method to get Spring bean, but I don’t like add Java code into JSP file.
Here have a method, you can get Spring bean in JSP file without Java code.
Setup a Spring Web MVC XML file and add 1 property in viewResolver:
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="exposeContextBeansAsAttributes" value="true"/> </bean>
Now, You can get bean content in JSP like that:
<c:out value="${ bean.value }" />
Spring will auto inject all bean into JSP file.