I've been pulling my hair for hours on this one.
I am setting up a new Spring MVC REST servlet and I've been trying to avoid XML definitions this time and do it programatically.
To the problem: I am looking for a way to load bean definitions from applicationContext.xml while still having #ComponentScan(...) enabled (#Autowire/context.getBean(...) works in the latter).
I looked through the google trying countless combinations (I think, but I may have missed something) and found something that could help:
https://www.mkyong.com/spring/spring-mixing-xml-and-javaconfig/
... only it doesn't (#ImportResource("classpath*:applicationContext")).
Please bear in mind that following declarations to #ImportResource fail the deployment of artifact (built with Gradle) with no log whatsoever:
"applicationContext"
"classpath:applicationContext"
The application context is located just next to 'java' folder (Gradle folder structure [src/main/java]):
My root config:
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Controller;
#Configuration
#ImportResource("classpath:applicationContext.xml")
#ComponentScan(
basePackages = { "com.storfoome.backend" },
excludeFilters = {#Filter(classes = { Controller.class }, type = FilterType.ANNOTATION)}
)
public class ServiceRootConfig {
}
My web config:
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#EnableWebMvc
#Configuration
#ComponentScan(
basePackages = { "com.storfoome.backend" },
useDefaultFilters = false,
includeFilters = { #Filter(classes = { Controller.class }, type = FilterType.ANNOTATION) }
)
public class ServiceWebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("*/resources/**").addResourceLocations("/resources/");
}
}
My servlet initializer:
import com.storfoome.backend.framework.rest.config.ServiceRootConfig;
import com.storfoome.backend.framework.rest.config.ServiceWebConfig;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SofomeServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
private static final String DEFAULT_SERVLET_MAPPING = "/sofome/*";
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { ServiceRootConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {ServiceWebConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[] { DEFAULT_SERVLET_MAPPING };
}
}
The bean with #Autowire from XML declared bean:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component("autowireTest")
public class AutowireTest {
#Autowired
private SofomePropertyResource propertyResource;
public void printProperty() {
System.out.println(propertyResource.getProperty("helloWorld"));
}
public AutowireTest() {
}
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
My applicationContext.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="sofomeProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath*:sofome.properties</value>
</list>
</property>
</bean>
</beans>
So, while I was posting this I also resolved this. So for anyone whould would be struggling with this.
Everything related to Java code in the question is correct apparently.
The thing was, with Gradle and it's "war" plugin. So, it looks into 'resource' folder by default for everything not *.java [citation needed].
I moved the applicationContext.xml to 'resource/config', launched Gradle build process (NOTE: I do not have any custom script written for WAR generation. Just "apply plugin: 'war'"):
Related
I am trying to use the properties file and inject it to my fields of a class, but I am getting null .
I have created a properties file called fortune.properties:
fortune1=Have a good day
fortune2=Have a bad day
fortune3=Have a medioccure day
Then I am loading it in the applicationContext.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Enable Component Scanning -->
<context:component-scan base-package="com.luv2code.springdemo"></context:component-scan>
<context:property-placeholder location="classpath:fortune.properties" />
</beans>
In the RandomFortuneClass, I am using value injection using #Value() annotation:
package com.luv2code.springdemo;
import java.util.Random;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component()
public class RandomFortuneService implements FortuneService {
#Value("${fortune1}")
private String fortune1;
#Value("${fortune2}")
private String fortune2;
#Value("${fortune3}")
private String fortune3;
String[] fortunes = new String[] {fortune1, fortune2, fortune3};
private Random random = new Random();
#Override
public String getFortune() {
int index = random.nextInt(fortunes.length);
return fortunes[index];
}
}
Then I am declaring fortuneService in SwimCoach class using constructor injection:
package com.luv2code.springdemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component()
public class SwimCoach implements Coach {
private FortuneService fortuneService;
#Autowired
SwimCoach(#Qualifier("randomFortuneService") FortuneService fs) {
fortuneService = fs;
}
#Override
public String getDailyWorkout() {
System.out.println();
return "Swim 5m everyday";
}
#Override
public String getDailyFortune() {
return fortuneService.getFortune();
}
}
Now when I try to call the method getDailyFortune in the AnnotationDemoApp class, I always get null as output.
package com.luv2code.springdemo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AnnotationDemoApp {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Coach theCoach = context.getBean("swimCoach", Coach.class);
System.out.println(theCoach.getDailyFortune());
context.close();
}
}
What is the error here?
Kindly comment if more information is needed.
Here is my file hierarchy:
PS: I am following the spring & hibernate course for beginners by Chad Darby.
You simply need to move fortune.properties into /src/main/resources, but let me suggest a cleaner way...
First, drop the xml configuration, it's outdated by several years and everything you can do there can be done via java annotations.
Second, add your property files to src/main/resources.
Third, tell Spring where to resolve your properties from, you can do this by adding #PropertySources({#PropertySource("fortune.properties")}) to a configuration class like this (also note that I've added the #ComponentScan and #Configuration annotations here):
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
#Configuration
#ComponentScan
#PropertySource("fortune.properties")
public class Config {
}
Fourth, in your main method, use the AnnotationConfigApplicationContext as opposed to the ClassPathXmlApplicationContext. I think you'll find it's much cleaner.
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
Coach theCoach = context.getBean("swimCoach", Coach.class);
System.out.println(theCoach.getDailyFortune());
}
So, I'm trying to learn Spring Framework, but currently I'm stuck on this problem, for some reason my mappings don't work and when I try to access that address I'm getting a 404 error.
Can someone please clarify what I'm doing wrong (both in usage of spring classes and the source of the problem I have described above)?
I'm configuring spring using the example shown in this video: YouTube Video, the code is basically the same, the only difference is package name and the location of the JSP file (could this be the source of my problem?).
The project was made in IntelliJ Idea and is attached to the following link (Google Drive): Project Link
As my servlet container I'm using Tomcat8 (tried both 9 and 8.5, no cigar).
HomeController.java
package com.demo.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
package com.demo.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by ARTERC on 1/16/2017.
*/
#Controller
public class HomeController {
#RequestMapping("/")
public String home() {
return "home";
}
}
WebInit.java
package com.demo.spring.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
#Configuration
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebConfig.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
WebConfig.java
package com.demo.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("com.demo.spring")
public class WebConfig extends WebMvcConfigurerAdapter{
#Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/");
resolver.setSuffix(".jsp");
return resolver;
}
}
home.jsp path: /web/home.jsp
Okay, so I found the solution.
Add war plugin to pom.xml
Fix web resource directory path (was webapp) Image Link
Due to project requirements I have to deploy a Spring application to a server incapable of running Tomcat and only capable of running WildFly. When I had a very simple project running on Tomcat and the root URL was hit (localhost:8080) it rendered my index.html. Since migrating to WildFly and refactoring the structure of my project, localhost:8080 no longer renders the index.html but I can still reach other URLs.
I've tried to implement a jboss-web.xml file under BrassDucks/src/main/webapp/WEB-INF/jboss-web.xml like this:
<jboss-web>
<context-root>Brass-Ducks</context-root>
</jboss-web>
Where Brass-Ducks is the artifactID but to no avail.
Consider my ApplicationConfig.java
package brass.ducks;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class ApplicationConfig extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(ApplicationConfig.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(applicationClass);
}
private static Class<ApplicationConfig> applicationClass = ApplicationConfig.class;
}
#RestController
class GreetingController {
#RequestMapping("/hello/{name}")
String hello(#PathVariable String name) {
return "Hello, " + name + "!";
}
}
and consider my Controller.java
package brass.ducks.application;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/")
public class Controller {
#RequestMapping("/greet")
#ResponseBody
public String greeting() {
return "Hello, there.";
}
}
And finally should it be relevant, my folder structure:
localhost:8080/greet returns "Hello, there" and localhost:8080/hello/name returns "Hello name". How can I fix this?
Depending on your exact configuration something along the lines of this should work:
#Controller
public class LandingPageController {
#RequestMapping({"/","/home"})
public String showHomePage(Map<String, Object> model) {
return "/WEB-INF/index.html";
}
}
This is going to explicitly map / to index.html.
I am trying create an project with and without spring xml configurations.
First at all, I create my xml configuration like that:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<bean id="memoryManagerProduct" class="br.com.caelum.stock.ProductManager">
<constructor-arg ref="memoryProductDAO"/>
</bean>
<bean id="memoryProductDAO" class="br.com.caelum.stock.dao.MemoryProductDAO"/>
</beans>
That I created my non XML configuration (I do not know if is right base in the fact that I do not know how invoke that)
package br.com.caelum.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import br.com.caelum.stock.ProductManager;
import br.com.caelum.stock.dao.MemoryProductDAO;
import br.com.caelum.stock.dao.Persistable;
import br.com.caelum.stock.model.Product;
#Configuration
public class AppConfig {
#Bean
public Persistable<Product> memoryProductDAO(){
return new MemoryProductDAO();
}
#Bean
public ProductManager memoryProductManager(){
return new ProductManager(memoryProductDAO());
}
}
Than I created an JUnit test:
package br.com.caelum.stock;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import br.com.caelum.stock.model.Product;
public class ProductManagerTest {
private ProductManager manager;
#Test
public void testSpringXMLConfiguration() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");
manager = (ProductManager) context.getBean("memoryManagerProduct");
Product product = new Product();
product.setDescription("[Book] Spring in Action");
product.setQuantity(10);
manager.add(product);
assertThat(manager.getProducts().get(0).getDescription(), is("[Book] Spring in Action"));
}
#Test
public void testSpringWithoutXMLConfiguration() {
ApplicationContext context = ?
}
}
How can I inject the configurations that are in my AppConfig to do a similar test as in my testSpringXMLConfiguration?
There are good examples in the Spring reference guide here: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-java-instantiating-container
In short, you would do this:
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
manager = (ProductManager) context.getBean("memoryManagerProduct");
However a better way of testing with Spring would be to use the spring-test support, details are here - http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html#integration-testing-annotations
You can do something like this with spring-test support:
#ContextConfiguration(classes = AppConfig.class)
#RunWith(SpringJUnit4ClassRunner.class)
public class ProductManagerTest {
#Autowired
private ProductManager manager;
#Test
public void testSpringXMLConfiguration() {
//use the productmanager in a test..
}
}
Is it possible in Spring 3.1.1 to configure a view resolver using Java annotations?
I am done with all configurations using Java annotations, but I am stuck at view resolver.
Code
package com;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#ComponentScan("com")
public class AppConfig
{
{
//Other bean declarations
}
#Bean
public UrlBasedViewResolver urlBasedViewResolver()
{
UrlBasedViewResolver res = new InternalResourceViewResolver();
res.setViewClass(JstlView.class);
res.setPrefix("/WEB-INF/");
res.setSuffix(".jsp");
return res;
}
}
I used this code and ran the application, but it's not returning the appropriate view. However, if I configure a viewresolver in the app-servlet.xml file, it works fine.
Your class should extend WebMvcConfigurerAdapter class. please have a look at below example
#Configuration
#ComponentScan(basePackages="com")
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
I tested your scenario with Spring 4.3.4 and it is working ok.
I would suggest double checking packages you scan and that AppConfig is properly provided.
I am attaching all files starting from your AppConfig. Yet it is good to extend WebMvcConfigurerAdapter. The source code attached is not ideal, it s simplistic and only to try to reproduce the problem you have reported.
Starting from AppConfig:
package com;
import org.springframework.context.annotation.*;
import org.springframework.web.servlet.view.*;
#Configuration
#ComponentScan("com")
public class AppConfig {
#Bean
public UrlBasedViewResolver getViewResovler() {
UrlBasedViewResolver urlBasedViewResolver = new UrlBasedViewResolver();
urlBasedViewResolver.setViewClass(JstlView.class);
urlBasedViewResolver.setPrefix("/WEB-INF/jsp/");
urlBasedViewResolver.setSuffix(".jsp");
return urlBasedViewResolver;
}
}
Then:
package com;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { AppConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Finally:
package com;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class MainController {
#RequestMapping("/")
public ModelAndView asdf() {
return new ModelAndView("ABC");
}
}
The problem with the above is that the DispatcherServlet.initViewResolvers get's called before the bean getViewResolver is defined and it cannot find the bean so it never adds the view resolver.
If you move the bean definition into an xml definition, it get's picked up. For some reason the MvcConfiguration class you have defined does not trigger a DispatcherServlet refresh if there are no ViewResolvers defined in the XML.