Rectangle 27 9

<context-param>
    <param-name>contextClass</param-name>
    <param-value>
      org.springframework.web.context.support.AnnotationConfigWebApplicationContext
  </param-value>
</context-param>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>xxx.xxx.configuration.ApplicationConfiguration</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>SpringApplication</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>xxx.xxx.controllers.HelloController</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>SpringApplication</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
@Configuration
public class ApplicationConfiguration {
  @Bean
  HelloService helloService () {
    return new HelloServiceImpl();
  }
}

and simple controller:

@Component
@Path("/helloController")
public class HelloController {

  @Autowired
  @Qualifier("helloService")
  private HelloService helloService ;


   @GET
   @Path("/hello")
   public String hello() {
    helloService.service();
  }
}

remember about excluding old Spring dependencies you may have some conflicts if you don't. You can do this same as on the example below or through DependencyManagement.

<dependencies>

    <!-- Jersey -->

    <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-spring3</artifactId>
        <version>2.11</version>
        <exclusions>
            <exclusion>
                <artifactId>spring-context</artifactId>
                <groupId>org.springframework</groupId>
            </exclusion>
            <exclusion>
                <artifactId>spring-beans</artifactId>
                <groupId>org.springframework</groupId>
            </exclusion>
            <exclusion>
                <artifactId>spring-core</artifactId>
                <groupId>org.springframework</groupId>
            </exclusion>
            <exclusion>
                <artifactId>spring-web</artifactId>
                <groupId>org.springframework</groupId>
            </exclusion>
            <exclusion>
                <artifactId>jersey-server</artifactId>
                <groupId>org.glassfish.jersey.core</groupId>
            </exclusion>
            <exclusion>
                <artifactId>
                    jersey-container-servlet-core
                </artifactId>
                <groupId>org.glassfish.jersey.containers</groupId>
            </exclusion>
            <exclusion>
                <artifactId>hk2</artifactId>
                <groupId>org.glassfish.hk2</groupId>
            </exclusion>
        </exclusions>
    </dependency>

    <!-- Spring 4 dependencies -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.0.6.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.0.6.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.0.6.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.0.6.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>4.0.6.RELEASE</version>
    </dependency>

</dependencies>

can you please share this code? as example, for example. :)

AFAIK the @Component annotation is only required if you need Spring functionality that requires proxying, such as @Transactional.

what kind of a project do we have to create in order to use jersey and spring? I tried creating a dynamic web project and i did not get any pom.xml file. in what file do we have to add the above mentioned dependencies and exclusions?

In Eclipse I use plugin: 'M2E - Maven Integration for Eclipse'. Then you can right click on your project -> Configure -> Convert to Maven project. Then you will see the pom.xml file.

Integrating Jersey 2 and Spring with Java Based Configuration - Stack ...

java spring rest jersey-2.0
Rectangle 27 5

Spring container is trying to find springSecurityFilterChain bean in application context, not web application context. Change spring security configuration to be included in root context.

Please provide more details as to how you think this problem can be resolved. ie specifically where in what files should the definition for the filter go? Thanks

No. I have never been able to resolve the issue. Still struggling with that.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

spring - org.springframework.beans.factory.NoSuchBeanDefinitionExcepti...

java spring spring-mvc spring-security
Rectangle 27 5

JdbcTemplate(DataSource dataSource)

You can try this way

@PropertySource("classpath:jdbc.properties")
@Configuration
public class Config {

    @Autowired
    private Environment env;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean(name = "dataSource")
    public DataSource dataSource() {
        BasicDataSource datasource = new BasicDataSource();
        datasource.setDriverClassName(env.getProperty("jdbc.driverClassName"));

//      Similarly other values
//      datasource.setUrl(url);
//      datasource.setUsername(username);
//      datasource.setPassword(password);
        return datasource;
    }

    @Bean(name = "jdbcTemplate")
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSource());
    }
}

Injecting bean dependencies with Spring Java based configuration - Sta...

java spring dependency-injection inversion-of-control spring-java-config
Rectangle 27 1

You don't need to create jdbcTemplate in the configuration. You could create it in the DAO class.

private JdbcTemplate jdbcTemplate;

@Autowired
public void setDataSource(final DataSource dataSource) {
    jdbcTemplate = new JdbcTemplate(dataSource);
}

Injecting bean dependencies with Spring Java based configuration - Sta...

java spring dependency-injection inversion-of-control spring-java-config
Rectangle 27 2

In the scope of DI container, I consider annotation based DI is abusing the use of Java annotation. By saying that, I don't recommend to use it widely in your project. If your project does really needs the power of DI container, I would recommend to use Spring IoC with Xml based configuration option.

If it is just for a sake of Unit-test, developers should apply Dependency Inject pattern in their coding and take advantages from mocking tools such as EasyMock or JMock to circumvent dependencies.

You should try to avoid using DI container in its wrong context.

java - Xml configuration versus Annotation based configuration - Stack...

java xml spring annotations
Rectangle 27 2

In the scope of DI container, I consider annotation based DI is abusing the use of Java annotation. By saying that, I don't recommend to use it widely in your project. If your project does really needs the power of DI container, I would recommend to use Spring IoC with Xml based configuration option.

If it is just for a sake of Unit-test, developers should apply Dependency Inject pattern in their coding and take advantages from mocking tools such as EasyMock or JMock to circumvent dependencies.

You should try to avoid using DI container in its wrong context.

java - Xml configuration versus Annotation based configuration - Stack...

java xml spring annotations
Rectangle 27 6

  • The XML configuration is at one place, instead of being scattered all over the source code in case of annotations. Some people may argue that IDEs like STS allow you to look at all annotations based configuration in one place, but I never like having dependencies on IDEs.
  • Its takes a little more efforts to write XML config, but it saves a lot of time later when you search for dependencies and try to understand the project.
  • XML keeps configuration well organized and simple. Hence is easier to understand, it helps new relatively inexperienced team members get up to speed quickly.
  • Allows you to change the config without a need to recompile and redeploy code. So it is better, when it comes to production support.

So in short XML configuration takes a little more efforts, but it saves you a lot of time & headache later in big projects.

java - Spring annotation-based DI vs xml configuration? - Stack Overfl...

java spring configuration dependency-injection annotations
Rectangle 27 11

aweigold got me most of the way there, but to concretely outline a solution for Spring 3.1 Java based configuration, here's what I did.

Register your GsonHttpMessageConverter with the message converters in your MVC config.

@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(new GsonHttpMessageConverter());
  }
}

The Spring docs outline this process, but aren't crystal clear. In order to get this to work properly, I had to extend WebMvcConfigurerAdapter, and then override configureMesageConverters. After doing this, you should be able to do the following in your controller method:

@Controller
public class AppController {
  @RequestMapping(value = "messages", produces = MediaType.APPLICATION_JSON_VALUE)
  public List<Message> getMessages() {
    // .. Get list of messages
    return messages;
  }
}

Thank you, this really helped me! With Spring 3.2.2 and jackson I could not get rid of the problem where it says: 406 not accaptable. I did this and it worked, but I also had to add <context:annotation-config/> to the service xml file.

json - Spring MVC mapping view for Google-GSON? - Stack Overflow

json spring spring-mvc gson
Rectangle 27 15

This is, unfortunately, a lot harder than it should be. In my application I accomplished this by doing the following:

This works because the context files are specified as input the the bean responsible for loading them. It won't work if you just try to do an import, as you mentioned, but this has the same effect with slightly more work. The bootstrap class looks something like this:

public class Bootstrapper implements ApplicationContextAware, InitializingBean {

    private WebApplicationContext context;
    private String[] configLocations;
    private String[] testConfigLocations;
    private boolean loadTestConfigurations;

    public void setConfigLocations(final String[] configLocations) {
        this.configLocations = configLocations;
    }

    public void setTestConfigLocations(final String[] testConfigLocations) {
        this.testConfigLocations = testConfigLocations;
    }

    public void setLoadTestConfigurations(final boolean loadTestConfigurations) {
        this.loadTestConfigurations = loadTestConfigurations;
    }

    @Override
    public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
        context = (WebApplicationContext) applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        String[] configsToLoad = configLocations;

        if (loadTestConfigurations) {
            configsToLoad = new String[configLocations.length + testConfigLocations.length];
            arraycopy(configLocations, 0, configsToLoad, 0, configLocations.length);
            arraycopy(testConfigLocations, 0, configsToLoad, configLocations.length, testConfigLocations.length);
        }

        context.setConfigLocations(configsToLoad);
        context.refresh();
    }
}

Basically, get the application context, set its config locations, and tell it to refresh itself. This works perfectly in my application.

Note: This code was taken from a working system, but I scrubbed it manually of some small bits and pieces related to the system itself. Apologize if there are any errors.

Thanks, but unfortunately I don't have complete control of the startup as an EJB is the entrypoint to the application. Maybe I should just upgrade to Spring 3 and use the JavaConfig instead :)

I don't think you need any control other than being able to tell the EJB which spring context to load. Am I missing something?

I'm surprised this solution wasn't accepted. It's simple and brilliant

I would agree with Sean. @Louis smart stuff indeed.

java - Import Spring config file based on property in .properties file...

java spring configuration
Rectangle 27 2

Java based configuration solution to prevent truncation (using a not-deprecated class):

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@Configuration
public class PolRepWebConfig extends WebMvcConfigurationSupport {

    @Override
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        final RequestMappingHandlerMapping handlerMapping = super
                .requestMappingHandlerMapping();
        // disable the truncation after .
        handlerMapping.setUseSuffixPatternMatch(false);
        // disable the truncation after ;
        handlerMapping.setRemoveSemicolonContent(false);
        return handlerMapping;
    }
}

I realized having some problems with Spring Boot auto-configuration when I used the approach above (some auto-configuration doesn't get effective).

BeanPostProcessor
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPostProcessor implements BeanPostProcessor {
    private static final Logger logger = LoggerFactory
            .getLogger(MyBeanPostProcessor.class);

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        if (bean instanceof RequestMappingHandlerMapping) {
            setRemoveSemicolonContent((RequestMappingHandlerMapping) bean,
                    beanName);
            setUseSuffixPatternMatch((RequestMappingHandlerMapping) bean,
                    beanName);
        }
        return bean;
    }

    private void setRemoveSemicolonContent(
            RequestMappingHandlerMapping requestMappingHandlerMapping,
            String beanName) {
        logger.info(
                "Setting 'RemoveSemicolonContent' on 'RequestMappingHandlerMapping'-bean to false. Bean name: {}",
                beanName);
        requestMappingHandlerMapping.setRemoveSemicolonContent(false);
    }

    private void setUseSuffixPatternMatch(
            RequestMappingHandlerMapping requestMappingHandlerMapping,
            String beanName) {
        logger.info(
                "Setting 'UseSuffixPatternMatch' on 'RequestMappingHandlerMapping'-bean to false. Bean name: {}",
                beanName);
        requestMappingHandlerMapping.setUseSuffixPatternMatch(false);
    }
}

java - Spring MVC @PathVariable getting truncated - Stack Overflow

java spring rest spring-mvc get
Rectangle 27 2

Java based configuration solution to prevent truncation (using a not-deprecated class):

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@Configuration
public class PolRepWebConfig extends WebMvcConfigurationSupport {

    @Override
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        final RequestMappingHandlerMapping handlerMapping = super
                .requestMappingHandlerMapping();
        // disable the truncation after .
        handlerMapping.setUseSuffixPatternMatch(false);
        // disable the truncation after ;
        handlerMapping.setRemoveSemicolonContent(false);
        return handlerMapping;
    }
}

I realized having some problems with Spring Boot auto-configuration when I used the approach above (some auto-configuration doesn't get effective).

BeanPostProcessor
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPostProcessor implements BeanPostProcessor {
    private static final Logger logger = LoggerFactory
            .getLogger(MyBeanPostProcessor.class);

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        if (bean instanceof RequestMappingHandlerMapping) {
            setRemoveSemicolonContent((RequestMappingHandlerMapping) bean,
                    beanName);
            setUseSuffixPatternMatch((RequestMappingHandlerMapping) bean,
                    beanName);
        }
        return bean;
    }

    private void setRemoveSemicolonContent(
            RequestMappingHandlerMapping requestMappingHandlerMapping,
            String beanName) {
        logger.info(
                "Setting 'RemoveSemicolonContent' on 'RequestMappingHandlerMapping'-bean to false. Bean name: {}",
                beanName);
        requestMappingHandlerMapping.setRemoveSemicolonContent(false);
    }

    private void setUseSuffixPatternMatch(
            RequestMappingHandlerMapping requestMappingHandlerMapping,
            String beanName) {
        logger.info(
                "Setting 'UseSuffixPatternMatch' on 'RequestMappingHandlerMapping'-bean to false. Bean name: {}",
                beanName);
        requestMappingHandlerMapping.setUseSuffixPatternMatch(false);
    }
}

java - Spring MVC @PathVariable getting truncated - Stack Overflow

java spring rest spring-mvc get
Rectangle 27 1

There are some pros and cons of annotation configuration from my experience:

  • When it comes to JPA configuration since it is done once and usually are not changed quite often I prefer to stick to annotation configuration. There maybe a concern regarding possibility to see a bigger picture of configuration - in this case I use MSQLWorkbench diagrams.
  • Xml configuration is very good to get a bigger picture of application but it maybe cumbersome to find some errors until runtime. In this case Spring @Configuration annotation sounds as a better choice since it let you see a bigger picture as well and also allows to validate configuration on compile time.
  • As for Spring configuration I prefer to combine both approaches: use @Configuration annotation with Services and Query interfaces and xml configuration for dataSource and spring configuration stuff like context:component-scan base-package="..."
  • But xml configuration bits java annotations when it comes to flow configuration(Spring Web Flow or Lexaden Web Flow) since it is extremely important to see a bigger picture of the whole business process. And it sounds cumbersome to have it implemented with annotations approach.

I prefer combining both approaches - java annotations and essential xml minimum that minimize configuration hell.

java - Xml configuration versus Annotation based configuration - Stack...

java xml spring annotations
Rectangle 27 1

There are some pros and cons of annotation configuration from my experience:

  • When it comes to JPA configuration since it is done once and usually are not changed quite often I prefer to stick to annotation configuration. There maybe a concern regarding possibility to see a bigger picture of configuration - in this case I use MSQLWorkbench diagrams.
  • Xml configuration is very good to get a bigger picture of application but it maybe cumbersome to find some errors until runtime. In this case Spring @Configuration annotation sounds as a better choice since it let you see a bigger picture as well and also allows to validate configuration on compile time.
  • As for Spring configuration I prefer to combine both approaches: use @Configuration annotation with Services and Query interfaces and xml configuration for dataSource and spring configuration stuff like context:component-scan base-package="..."
  • But xml configuration bits java annotations when it comes to flow configuration(Spring Web Flow or Lexaden Web Flow) since it is extremely important to see a bigger picture of the whole business process. And it sounds cumbersome to have it implemented with annotations approach.

I prefer combining both approaches - java annotations and essential xml minimum that minimize configuration hell.

java - Xml configuration versus Annotation based configuration - Stack...

java xml spring annotations
Rectangle 27 6

For the Spring 2.5 and 3.0, I have a similar solution to louis, however I've just read about 3.1's upcoming feature: property management, which sounds great too.

Does somebody have a working example of that ? Couldn't make it work with 3.1.1.

java - Import Spring config file based on property in .properties file...

java spring configuration
Rectangle 27 1

For Spring Framework I like the idea of being able to use the @Component annotation and setting the "component-scan" option so that Spring can find my java beans so that I do not have to define all of my beans in XML, nor in JavaConfig. For example, for stateless singleton java beans that simply need to be wired up to other classes (via an interface ideally) this approach works very well. In general, for Spring beans I have for the most part moved away from Spring XML DSL for defining beans, and now favor the use of JavaConfig and Spring Annotations because you get some compile time checking of your configuration and some refactoring support that you don't get with Spring XML configuration. I do mix the two in certain rare cases where I've found that JavaConfig/Annotations can't do what is available using XML configuration.

For Hibernate ORM (haven't used JPA yet) I still prefer the XML mapping files because annotations in domain model classes to some degree violates The Clean Architecture which is a layering architectural style I have adopted over the past few years. The violation occurs because it requires the Core Layer to depend on persistence related things such as Hibernate or JPA libraries and it makes the domain model POJOs a bit less persistence ignorant. In fact the Core Layer is not supposed to depend on any other infrastructure at all.

However, if The Clean Architecture is not your "cup of tea" then I can see there are definitely advantages (such as convenience and maintainability) of using Hibernate/JPA annotations in domain model classes over separate XML mapping files.

java - Xml configuration versus Annotation based configuration - Stack...

java xml spring annotations
Rectangle 27 1

For Spring Framework I like the idea of being able to use the @Component annotation and setting the "component-scan" option so that Spring can find my java beans so that I do not have to define all of my beans in XML, nor in JavaConfig. For example, for stateless singleton java beans that simply need to be wired up to other classes (via an interface ideally) this approach works very well. In general, for Spring beans I have for the most part moved away from Spring XML DSL for defining beans, and now favor the use of JavaConfig and Spring Annotations because you get some compile time checking of your configuration and some refactoring support that you don't get with Spring XML configuration. I do mix the two in certain rare cases where I've found that JavaConfig/Annotations can't do what is available using XML configuration.

For Hibernate ORM (haven't used JPA yet) I still prefer the XML mapping files because annotations in domain model classes to some degree violates The Clean Architecture which is a layering architectural style I have adopted over the past few years. The violation occurs because it requires the Core Layer to depend on persistence related things such as Hibernate or JPA libraries and it makes the domain model POJOs a bit less persistence ignorant. In fact the Core Layer is not supposed to depend on any other infrastructure at all.

However, if The Clean Architecture is not your "cup of tea" then I can see there are definitely advantages (such as convenience and maintainability) of using Hibernate/JPA annotations in domain model classes over separate XML mapping files.

java - Xml configuration versus Annotation based configuration - Stack...

java xml spring annotations
Rectangle 27 97

One way to do this is to have your configuration class extend WebMvcConfigurerAdapter, then override the following method as such:

@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

This answer is totally correct. However, if you're having issues (like I was) after adding this, remember that you might still need a default servlet handler described here: stackoverflow.com/a/17013442/2047962

Upvoted for the answer. Better if you can add explanation. That would be nice for a beginner.

@Menuka Explaination: Every request which begins with "/resources/**" path will be mapped to a files in a "/resources/" folder.

java - Annotation Configuration Replacement for mvc:resources - Spring...

java spring spring-mvc configuration
Rectangle 27 1

The issues I have faced have been resolved. I have resolved the isse of scanning the controllers via "@ComponentScan("my.package.containing.controllers.to.scan")"

Spring 3.1.1 java based configuration issue - Stack Overflow

spring spring-mvc tiles
Rectangle 27 1

What is is never / latest XML or Java config ?

Is doable completely by Java config or I have to mix up both Java and XML?

You can avoid using XML in latest versions of spring (i.e. 4 and later)

Startup time is not important for performance. Runtime performance is same.

In case of error in XML you will get exception with stacktrace. In most of cases it is enough.

Which Spring MVC XML or Java based configuration is recommended? - Sta...

java xml spring spring-mvc
Rectangle 27 1

Here is something that I found starting from various tutorials. Combined with other answers you should have a complete example.

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import com.sun.jersey.spi.spring.container.servlet.SpringServlet;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

public class WebInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(AppConfig.class);
        ctx.setServletContext(servletContext);
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx);
        ServletRegistration.Dynamic servlet = servletContext.addServlet("jersey-serlvet", new SpringServlet());
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
    }
}

Integrating Jersey 2 and Spring with Java Based Configuration - Stack ...

java spring rest jersey-2.0