I'm new to Spring MVC and Hibernate. I'm trying to start a project by following tutorials but I have been running into problems as my project structure is not consistent with the tutorials I am reading.
I have downloaded the latest STS and I do see the option of creating an Spring MVC project. However it is based on Spring 3 and still uses XML files. From what I have read it looks like there is a way to do it without XML files since Spring 3. I prefer annotations over XML files greatly.
How can I create a Spring MVC 4 application that is based on annotations and relies on xml files minimally?
EDIT:
I want to create a web project
Here is a squeletal example of full java configuration. You will need :
a class extending AbstractAnnotationConfigDispatcherServletInitializer to replace the old web.xml file
one or more #Configuration annotaded class(es) to initialize the root context (replaces the old applicationContext.xml)
one or more #Configuration annotaded class(es) to initialize the DispatcherServlet context (replaces the old dispatcher-servlet.xml)
This is the web.xml :
public class WebAppConf extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
// declare root context configuration classes
return new Class<?>[]{ RootConf.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
// declare servlet context configuration classes
return new Class<?>[]{ ServletConf.class };
}
#Override
protected String[] getServletMappings() {
// mapping of DispatcherServlet
return new String[]{"/"};
}
#Override
protected void customizeRegistration(Dynamic registration) {
// additional configuration, here for MultipartConfig
super.customizeRegistration(registration);
MultipartConfigElement multipartConf = new MultipartConfigElement("", 200000L, -1L, 0);
registration.setMultipartConfig(multipartConf);
}
}
RootConf will declare business model, service and dao beans and is not shown here.
ServletConf declares the controllers and servlet configuration :
#Configuration
#EnableWebMvc
// declare where to find annotated controllers
#ComponentScan({"org.example.web"})
public class ServletConf extends WebMvcConfigurerAdapter {
#Bean
MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
#Bean
ViewResolver internalViewResolver() {
// the view resolver bean ...
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
}
As said above, it is squeletal, but it comes from a working minimal example so you should be able to start with that and extend it at will. In my example, the above three classes live in a org.example.config package that will never be scanned for autodetecting other configuration classes or annotated beans.
Hope it helps ...
I know this doesn't answer your question fully, but hopefully the links will be useful.
WebApplicationInitializer - A 100% code based approach to configuration
as well as AnnotationConfigWebApplicationContext
Also, if you have the time, reading the relevant sections of Spring's MVC chapter of their documentation is helpful.
I Wish that this link will be helpful for you Spring security with annotation Mkyong
The latest versions of STS integrate the Spring guides from https://spring.io/guides directly, try the "Import Spring Getting Started Content" wizard. There are good guides included for creating a Spring Boot based web service, for example, among many others.
Related
I'm unable to load spring.data configuration from application.properties in Spring WebFlux
Here's what I added in application.properties
spring.data.web.pageable.default-page-size=2
spring.data.web.pageable.max-page-size=2147483647
The same properties work in Spring MVC
Inside SpringDataWebAutoConfiguration, there is #ConditionalOnClass({PageableHandlerMethodArgumentResolver.class, WebMvcConfigurer.class}) which may be the cause why it's not loaded in Spring WebFlux because it doens't have WebMvcConfigurer
Is it the problem?
How to load the properties in WebFlux?
In Spring Webflux there is currently no customization available of the ReactivePageableHandlerMethodArgumentResolver with properties but you can customize it via WebFluxConfigurer.
#Configuration
class WebFluxConfiguration implements WebFluxConfigurer {
#Override
public void configureArgumentResolvers(ArgumentResolverConfigurer configurer) {
var pageableResolver = new ReactivePageableHandlerMethodArgumentResolver();
pageableResolver.setMaxPageSize(Integer.MAX_VALUE);
pageableResolver.setFallbackPageable(PageRequest.of(0, 2));
configurer.addCustomResolver(pageableResolver);
}
}
You could also create your own properties binding with Configuration Properties now and pass the values to the setters.
I am using plain vanilla JAXRS in a provided Application Server with Swagger 1.5.18. I can get the Swagger annotated classes to appear in the swagger.json, but I am having trouble setting the Swagger to scan for non annotated classes, those with just the #Path JAXRS annotations.
I currently have the BeanConfig in the Class that is extending Application. I tried using a Servlet that extended DefaultJaxrsConfig with #WebInitParam(name="scan.all.resources", value="true") but that did not work at all.
The documentation states that setting ReaderConfig.scanAllResources would achieve what I am looking for. However, I am not sure of a good way to implement this. Any suggestions?
Current configuration class:
#ApplicationPath("services")
public class Configuration extends Application {
public Configuration() {
BeanConfig beanConfig = new BeanConfig();
beanConfig.setVersion("1.0.0");
beanConfig.setTitle("SwaggerExample");
beanConfig.setBasePath("/SwaggerExample/services");
beanConfig.setResourcePackage("com.xxxxxx.swagger.jaxrs");
beanConfig.setScan(true);
beanConfig.setPrettyPrint(true);
}
Thanks, Brian
I did find a way around the issue as posted in the Swagger blog post, by implementing a ReaderListener. However, I would think this could be set at the BeanConfig level. Here is my solution:
#SwaggerDefinition
public class ApiDefinitions implements ReaderListener {
#Override
public void afterScan(Reader reader, Swagger swagger) {
}
#Override
public void beforeScan(Reader reader, Swagger swagger) {
((DefaultReaderConfig) reader.getConfig()).setScanAllResources(true);
}
}
Brian
I am using Swagger with Jersey 2 and spring bootstrap. Currently I'm looking a solution to disable swagger on production as it will be concern in case any user
uses the API's with the swagger UI.
I'm registering io.swagger.jersey.config.JerseyJaxrsConfig servlet in web.xml and passing init parameters to it like api.version and swagger.api.basepath. Along with this I'm registering package to scan as io.swagger.jaxrs.listing so that org.glassfish.jersey.server.ResourceConfig will take care to prepare swagger UI.
I got to know from internet that we can achive this byb using #profile annotations. But I experienced that If we register any class in Web.xml, even though you are using #Profile on that class level, it will not work as the class going to be loaded at context load.
I have static contents in my project like swagger-ui-min.js, swagger-ui.js, index.html etc to load the swagger.
With this setup, how can I disable swagger UI in production? Also if some one have experience on , should swagger could be disabled in production or not?
You could have a flag which allows to load the Swagger Servlet only when you are not in production (here for Swagger 2):
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
import io.swagger.jaxrs2.integration.resources.OpenApiResource;
#ApplicationPath("") // no application path after the context root
public class MyApp extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<>();
classes.add(...); // your main service
if (notInProduction) { // a flag telling that you are not in production
classes.add(OpenApiResource.class);
}
return classes;
}
}
Below code worked for me.
String enable_swagger_ui = System.getenv("ENABLE_SWAGGER_UI");
if( enable_swagger_ui != null && enable_swagger_ui.equalsIgnoreCase("true"))
packages("io.swagger.jaxrs.listing");
You just need to add the ENABLE_SWAGGER_UI in system environment variable where you want to enable swagger.
Hi I am new to Spring MVC i am following Spring reference documentaion I have doubt in view resolver. Here is my sample code.
#Controller
#RequestMapping("/form")
public class MyController {
#RequestMapping(method = RequestMethod.GET)
public String setupForm() {
// do my stuff
return "myform";
}
#RequestMapping(method = RequestMethod.POST)
public String processForm(ModelMap model) {
// process form data
model.addAttribute("notification", "Successfully did it!");
return "redirect:/form";
}
}
here i am using two controllers, the first one returns "myform" and second one returns "redirect:/form". My question is, what is the difference between these two and how it works?
If you are familiar with jsp servlet, I think you can know the difference between redirect and forward, or you can get tons of answers from google. Then I want to explain a bit about how Spring does this. in setupForm method, it returns myform, then according to your view resovler configuration, it will try to find a myform.jsp or another likes this, and if your view resovler is internalresourceviewresovler, Spring will do a forward automatically and try to find this jsp in web-inf directory, if not, you have to specify a forward prefix. and for processForm method, that after return redirect:/form, it will force browser to send a new request /form to server which can be got by spring mvc and it will handle it with the related method.
I have my Wicket 1.4 code to have a link to download a file which is generated programatically:
protected class MyWebResource extends WebResource {
public IResourceStream getResourceStream() {
.....
return new StringResourceStream(myString, "text/plain");
}
}
ResourceLink<?> downloadLink =
new ResourceLink<Object>("downloadLink", new MyWebResource());
Everything was good. Now I've upgrade to Wicket 1.5. Now WebResource doesn't exist any more.
I've searched the web for ages, surely this must be a simple problem which has a simple solution? Alas I can't find it.
The replacement is AbstractResource. Basically you should create ResourceResponse and do what you did in its WriteCallback.
See the specializations of AbstractResource in Wicket's code for examples.
See http://wicketinaction.com/2011/07/wicket-1-5-mounting-resources/ as well.