Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache Tiles - Unable to access beans in a custom ViewPreparer in Spring MVC

I am using Spring 3.2 with Apache Tiles. I generated a lot of my service classes using Roo. I am trying a simple procedure where I inject a variable into the jsp templates. That part works fine, but I am stuck at the point where I need to reference a service bean.

@Component
public class CustomViewPreparer implements ViewPreparer {

@Autowired
UserProfileService ups;

@Override
public void execute(TilesRequestContext tilesContext,
                    AttributeContext attributeContext) {

       Authentication a = SecurityContextHolder.getContext().getAuthentication();
       String name = a.getName(); //get logged in username

       UserProfile up = ups.findByUsername(name);
       //request.setAttribute("isLoggedIn", up!=null);

    }
}

The UserProfileService "ups" is always null. I found this: http://forum.springsource.org/showthread.php?48950-ViewPreparer-is-triggered-before-Session-starts

But I don't understand the response. I can work around this by injecting my variable everytime I return a View, but I am curious how others have solved this problem.

like image 871
Peter Avatar asked Oct 04 '22 22:10

Peter


1 Answers

I had the same problem, the reason is because you have to say to Tiles to get the UserProfileService instance from spring bean.

So you have to do it to explictly ask to use spring bean for injection, in your TilesConfigurer :

<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
  <property name="definitions">
    <list>
     .....
    </list>
  </property>

  <!-- resolving preparer names as Spring bean definition names -->
  <property name="preparerFactoryClass"
       value="org.springframework.web.servlet.view.tiles2.SimpleSpringPreparerFactory "/>

</bean>

Go here to get more informations about the configration : http://static.springsource.org/spring/docs/2.5.x/reference/view.html

like image 104
julus Avatar answered Oct 11 '22 16:10

julus