I have a @Controller
that has a @RequestMapping
to map an endpoint to my jsp page. In that controller, I use a @ModelAttribute
annotation to make a @Bean
I have in my configuration file accessible in my jsp.
@Controller
public class WebPageController {
@Autowired
private MyBean myBean;
@ModelAttribute
public MyBean myBean() {
return myBean;
}
@RequestMapping("/mypage")
public String myPage() {
return "myPage";
}
}
In my config file, I have the @Bean
, and an InternalResourceViewResolver
.
@Configuration
@EnableWebMvc
@ComponentScan({"my.package"})
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public MyBean myBean {
return new MyBean();
}
@Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
return resolver;
}
}
This works fine and I can access myBean
on my jsp page.
<script type="text/javascript">
version = "${myBean.version}"
</script>
However, I want to move my controller into the Java Config. I can accomplish the same @RequestMapping
using a ViewController
in my WebConfig
.
@Override
public void addViewControllers(final ViewControllerRegistry viewControllerRegistry) {
viewControllerRegistry.addViewController("/myPage").setViewName("myPage");
}
Now, I need to add the myBean
as a @ModelAttribute
to be accessible on myPage.jsp
. How can I do this in the Java Config?
EDIT: This is not a duplicate of this question. That shows how you would do it with xml configuration. I would like to know how to do it in my Java @Configuration
file.