Development tools: idea java
Use the framework: spring + springmvc + mybatis + dubbo
dubbo is a high-performance, java based, open source RPC framework.
When I use spring #autowired error, as shown in Figure 1.
But when I was in java annotations, it works fine, as shown in Figure II.
Figure 1
Figure 2
code1. the spring/applicationContext-service.xml for service.
code2. the spring/spring-mvc.xml for contoller.
code3. Service
code4. Controller (Here's a problem, with #autowired can not be automatically injected)
Thanks!
The code:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd ">
<context:component-scan base-package="xyz.maojun.service"/>
<dubbo:application name="manager"/>
<dubbo:registry protocol="zookeeper"
address="localhost:2181"/>
<dubbo:protocol name="dubbo" port="20880"/>
<dubbo:service interface="xyz.maojun.service.ItemService" ref="itemServiceImpl" timeout="600000"/>
</beans>
More code:
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd ">
<context:component-scan base-package="xyz.maojun.controller"/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"value="/WEB-INF/jsp/"/>
<property name="suffix"value=".jsp"/>
</bean>
<mvc:resources mapping="/css/**"location="css/"/>
<mvc:resources mapping="/js/**"location="js/"/>
<dubbo:application name="manager-web"/>
<dubbo:registry protocol="zookeeper"address="localhost:2181"/>
<dubbo:reference interface="xyz.maojun.service.ItemService"id="itemService"/>
</beans>
ItemService code:
package xyz.maojun.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import xyz.maojun.common.pojo.EasyUIDateGridResult;
import xyz.maojun.mapper.TbItemMapper;
import xyz.maojun.pojo.TbItem;
import xyz.maojun.pojo.TbItemExample;
import xyz.maojun.service.ItemService;
import javax.annotation.Resource;
import java.util.List;
#Service
public class ItemServiceImpl implements ItemService {
#Autowired
private TbItemMapper tbItemMapper;
#Override
public TbItem getItemById(long itemid) {
TbItemExample example = new TbItemExample();
TbItemExample.Criteria criteria = example.createCriteria();
criteria.andIdEqualTo(itemid);
List<TbItem> list = tbItemMapper.selectByExample(example);
if (list != null && list.size() > 0) {
return list.get(0);
}
return null;
}
}
The controller:
package xyz.maojun.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import xyz.maojun.pojo.*;
import xyz.maojun.service.ItemService;
import javax.annotation.Resource;
#Controller
public class ItemController {
#Resource // i want to use #autowired ,but it not work
private ItemService itemService;
#RequestMapping("/item/{itemId}")
#ResponseBody
public TbItem getItemById(#PathVariable long itemId) {
TbItem tbItem = itemService.getItemById(itemId);
return tbItem;
}
}
I already got this answer, it is Intellij IDEA problem.When running the project does not have this error, I use the spring annotation, Intellij IDEA will can not find the bean then make an error. Ignore false positives
Related
I know this has been asked before, but none of the proposed answers work for me.
When starting up Jetty with Spring Security I get this error:
No bean named 'org.springframework.web.filter.DelegatingFilterProxy-1b68ddbd' available
applicationContext.xml:
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<context:component-scan base-package="de.pack.webservice" />
<context:annotation-config />
[...]
<jpa:repositories base-package="de.pack.webservice.security"
entity-manager-factory-ref="customEntityManagerFactory" />
</beans>
SecurityConfig.java
package de.pack.webservice.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.authentication.dao.ReflectionSaltSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import de.pack.webservice.security.StandardPasswordEncoder;
#EnableWebSecurity
#Configuration
#Import(PrePostEnabledConfig.class)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userService;
#Autowired
private StandardPasswordEncoder encoder;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userService);
authProvider.setPasswordEncoder(encoder);
ReflectionSaltSource saltSource = new ReflectionSaltSource();
saltSource.setUserPropertyToUse("salt");
authProvider.setSaltSource(saltSource);
auth.authenticationProvider(authProvider);
System.out.println("in gobal");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
System.out.println("in configure");
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable().authorizeRequests().anyRequest().authenticated()
.and().httpBasic();
}
}
And for Dev we don't use Web.xml but set the parameters at server startup. Here's the relevant part with the filter definition:
ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
contextHandler.setContextPath("/");
contextHandler.setInitParameter("contextConfigLocation", "classpath*:**applicationContext.xml");
contextHandler.addEventListener(new ResteasyBootstrap());
contextHandler.addEventListener(new SpringContextLoaderListener());
ServletHolder holder = new ServletHolder(new HttpServletDispatcher());
holder.setInitParameter("javax.ws.rs.Application", WebApplication.class.getName());
contextHandler.addServlet(holder, "/*");
EnumSet<DispatcherType> x = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE);
contextHandler.addFilter(DelegatingFilterProxy.class, "/*", x);
server.setHandler(contextHandler);
Configure the DelegatingFilterProxy as below:
context.addFilter(new FilterHolder(new DelegatingFilterProxy("springSecurityFilterChain")), "/*", x);
Actually Spring Security looks for a bean named springSecurityFilterChain (by default), which points to org.springframework.web.filter.DelegatingFilterProxy
I'm new to neo4j and spring in combination and spring at all. When I start debugging, I get the following exception:
Exception in thread "main"
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'getSessionFactory' available
Can anyone help me please?
apllication-context.xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/data/neo4j
http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="de.unileipzig.analyzewikipedia.neo4j" />
<!--neo4j:config storeDirectory="C:/temp/neo4jdatabase" base-package="de.unileipzig.analyzewikipedia.neo4j.dataobjects"/-->
<neo4j:repositories base-package="de.unileipzig.analyzewikipedia.neo4j.repositories"/>
<tx:annotation-driven />
<bean id="graphDatabaseService" class="org.springframework.data.neo4j.support.GraphDatabaseServiceFactoryBean"
destroy-method="shutdown" scope="singleton">
<constructor-arg value="C:/develop/uni/analyze-wikipedia-netbeans/database"/>
<constructor-arg>
<map>
<entry key="allow_store_upgrade" value="true"/>
</map>
</constructor-arg>
</bean>
</beans>
Startup-Class
package de.unileipzig.analyzewikipedia.neo4j.console;
import de.unileipzig.analyzewikipedia.neo4j.dataobjects.Article;
import de.unileipzig.analyzewikipedia.neo4j.service.ArticleService;
import java.io.File;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Neo4JConsole {
/**
* MAIN: start the java file
*
* #param args as string array
*/
public static void main(String[] args) {
String cwd = (new File(".")).getAbsolutePath();
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
ArticleService service = (ArticleService) context.getBean("articleService");
Article art = createArticle();
createArticle(service, art);
System.out.println("Article created");
}
private static Article createArticle() {
Article article = new Article();
article.setTitle("Title");
return article;
}
private static Article createArticle(ArticleService service, Article art) {
return service.create(art);
}
}
Thank you.
Do you have this configuration?
#Configuration
#EnableNeo4jRepositories("org.neo4j.cineasts.repository")
#EnableTransactionManagement
#ComponentScan("org.neo4j.cineasts")
public class PersistenceContext extends Neo4jConfiguration {
#Override
public SessionFactory getSessionFactory() {
return new SessionFactory("org.neo4j.cineasts.domain");
}
}
For more information, try to look here
I am trying to parameterize cron expression and reading it from properties file. During this process I get following exception "Error creating bean with name 'springScheduleCronExample': Initialization of bean failed; nested exception is java.lang.IllegalStateException: Encountered invalid #Scheduled method 'cronJob': Cron expression must consist of 6 fields (found 1 in "${cron.expression}")".
Then I found following post
Using that I cron expression is being read, only if I have
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SpringScheduleCronExample.class);
define in my main method. The issue that I am having is, I want to run this on server without main method, can anyone please help me with this.
Here is my applicationContext.xml
<?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:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<task:annotation-driven />
<util:properties id="applicationProps" location="application.properties" />
<context:property-placeholder properties-ref="applicationProps" />
<bean class="com.hemal.spring.SpringScheduleCronExample" />
</beans>
My SpringScheduleCronExample.java looks like this
package com.hemal.spring;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
#Configuration
#EnableScheduling
#PropertySource("classpath:application.properties")
public class SpringScheduleCronExample {
private AtomicInteger counter = new AtomicInteger(0);
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Scheduled(cron = "${cron.expression}")
public void cronJob() {
int jobId = counter.incrementAndGet();
System.out.println("Job # cron " + new Date() + ", jobId: " + jobId);
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SpringScheduleCronExample.class);
try {
Thread.sleep(24000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
context.close();
}
}
}
My application Properties has
cron.expression=*/5 * * * * ?
Here is how I got it to work
Application-context.xml
<?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:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<context:property-placeholder properties-ref="applicationProps" />
<context:annotation-config/>
<context:component-scan base-package="com.hemal.spring" />
<task:annotation-driven />
</beans>
MyApplicationConfig.java
package com.hemal.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
#Configuration
#EnableScheduling
#ComponentScan(basePackages = {"com.hemal.spring"})
#PropertySource("classpath:application.properties")
public class MyApplicationConfig {
#Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
properties.setLocation(new ClassPathResource( "application.properties" ));
properties.setIgnoreResourceNotFound(false);
return properties;
}
}
MyApplicationContext.java
package com.hemal.spring;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
public class MyApplicationContext implements WebApplicationInitializer{
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(MyApplicationConfig.class);
servletContext.addListener(new ContextLoaderListener(rootContext));
}
}
My scheduler class
package com.hemal.spring;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
public class SpringScheduleCronExample {
private AtomicInteger counter = new AtomicInteger(0);
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Scheduled(cron = "${cron.expression}")
public void cronJob() {
int jobId = counter.incrementAndGet();
System.out.println("Job # cron " + new Date() + ", jobId: " + jobId);
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SpringScheduleCronExample.class);
try {
Thread.sleep(24000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
context.close();
}
}
}
application.properties
cron.expression=0/5 * * * * ?
I tried to load data via AJAX in Spring 3.0, but the AJAX URL can't find the controller in Spring, and I don't know how to fix this.
I know while server start it looks up the URL and gets data but here I can't crate annotation properly in spring and I have searched the web a lot but have not succeeded.
My Java class:
package springactiontest;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import Dao.dao;
#Controller
//#RequestMapping("/employee")
public class mainclass {
#RequestMapping(value="/AddUser",method=RequestMethod.GET)
public #ResponseBody static String data(ModelMap model, HttpSession session) {
System.err.println("err ocured");
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
setvalueclass studentJDBCTemplate =(setvalueclass)context.getBean("actionclass");
System.out.println("------list district--------" );
JSONArray newtest=new JSONArray();
List<dao> students = studentJDBCTemplate.listStudents();
for (dao record : students)
{
JSONObject ob=new JSONObject();
System.out.print("ID test: " + record.getDistrict());
ob.put("distrct", record.getDistrict());
newtest.add(ob);
}
System.err.println("error");
String res=newtest.toString();
System.err.println("error"+res);
return res;
}
}
Jsp:
$("document").ready(function () {
alert("distrcict");
dist_pop();
});
function dist_pop() {
var urlService="http://tamilnilam:8080/SpringTest";
$.ajax({
url: urlService +'/AddUser',
type: 'GET',
dataType: 'jsonp',
contentType: "application/json",
success: function (data) {
alert("sucess")
},
error: function (jqXHR, exception) {
alert("Error Occured in dist pop");
}
});
}
applicationcontext.xml:
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="springactiontest.setvalueclass"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://10.163.2.165:5434/land_rural"/>
<property name="username" value="postgres"/>
<property name="password" value="postgres"/>
</bean>
<bean id="actionclass" class="springactiontest.setvalueclass">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
Looks like component-scan is missing, it helps Spring to detect and instantiate Spring beans which are annotated with #Component, #Service,#Repository, #Controller, #Endpoint etc
<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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.your.controller.package" />
// Rest of the bean defiantions
</beans>
For reference : Spring MVC tutorial
This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 5 years ago.
I'm having trouble autowiring a Spring bean in my application. This is something I've done before in other applications with success, but for some reason I'm getting stumped. I've googled around, and have found many folks having the same troubles, and the warnings that go along with using the getApplicationContext() approach but no answers that helped me. I understand the warnings and still have a case where I want to do it this way, then maybe I'll get it working using AspectJ and compile time weaving.
Here is my setup:
applicationContext.xml
<?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:oxm="http://www.springframework.org/schema/oxm"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<context:property-placeholder location="classpath:widgetClient.properties"/>
<context:component-scan base-package="com.myCompany.widget.domain" />
<context:component-scan base-package="com.myCompany.widget.services" />
<context:annotation-config />
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
<bean id="heartbeat" class="com.company.widget.domain.CheckWidgetServerHeartbeat" destroy-method="destroy">
<constructor-arg type="java.lang.Integer" name="interval" value="${heartbeat.interval}"/>
<constructor-arg type="java.lang.Integer" name="timeout" value="${heartbeat.timeout}"/>
<constructor-arg type="java.lang.Integer" name="unhealthyThreshold" value="${unhealthy.threshold}"/>
<constructor-arg type="java.lang.Integer" name="healthyThreshold" value="${healthy.threshold}"/>
<constructor-arg type="java.lang.Integer" name="backupVerifyTime" value="${backup.verify.time}"/>
<constructor-arg type="java.lang.String" name="apiServerUrl" value="${api.server.url}" />
</bean>
</beans>
BaseService.java
package com.company.widget.services;
import com.company.widget.domain.CheckWidgetServerHeartbeat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
#Component
public class BaseService{
#Autowired
private ApplicationContext appContext;
public BaseService(){}
public CheckWidgetServerHeartbeat getHeartbeat(){
return (CheckWidgetServerHeartbeat) appContext.getBean("heartbeat");
}
}
Heartbeatservice.java
package com.company.widget.services;
import org.springframework.stereotype.Service;
import org.apache.log4j.Logger;
#Service
public class HeartbeatService extends BaseService{
private static final Logger logger = Logger.getLogger(HeartbeatService.class);
public HeartbeatService(){}
public Boolean isHealthy(){
return getHeartbeat().check();
}
}
CompanyWidgetClient.java
package com.company.widget.domain;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Locale;
import java.util.ResourceBundle;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.*;
import com.company.widget.services.HeartbeatService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
#Component
public class CompanyWidgetClient{
#Autowired
private HeartbeatService heartbeatService;
public CompanyWidgetClient(String settingsXmlFilePath, HttpServletRequest request){
if(settingsXmlFilePath != null){
configuration = new CompanyWidgetConfiguration(settingsXmlFilePath, request);
}
if(request != null){
this.request = request;
}
//Use API server URL from settings file if it is present
if (configuration.getProperty("api_server_url") != null) {
this.apiServerUrl = configuration.getProperty("api_server_url");
log.debug("Set api_server_url to " + this.apiServerUrl + " which was found in settings.xml");
}
}
public CompanyWidgetClient(CompanyWidgetConfiguration configuration, HttpServletRequest request){
if(configuration != null){
this.configuration=configuration;
}
if(request != null){
this.request = request;
}
//Use API server URL from settings file if it is present
if (configuration.getProperty("api_server_url") != null) {
this.apiServerUrl = configuration.getProperty("api_server_url");
log.debug("Set api_server_url to " + this.apiServerUrl + " which was found in settings.xml");
}
}
public CompanyWidgetClient(){}
private CompanyWidgetResponse requestWidget(){
if(heartbeatService.isHealthy()){
do stuff...
}
index.jsp
<%# page import="com.company.widget.domain.*" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%
CompanyWidgetClient widgetClient = new CompanyWidgetClient("/WEB-INF/settings.xml", request);
String companyWidgetComponent = widgetClient.createWidget();
%>
...
HTML stuff
...
<div id="widget">
<%=companyWidgetComponent%>
</div>
...
The error:
500
org.apache.jasper.JasperException: An exception occurred processing JSP page /index.jsp at line 5
2: <%# page contentType="text/html;charset=UTF-8" language="java" %> 3: <% 4: CompanyWidgetClient widgetClient = new CompanyWidgetClient("/WEB-INF/settings.xml", request); 5: String companyWidgetComponent = widgetClient.createWidget(); 6: %> 7: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 8: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
java.lang.NullPointerException
com.company.widget.domain.CompanyWidgetClient.requestWidget(CompanyWidgetClient.java:553)
com.company.widget.domain.CompanyWidgetClient.createWidget(CompanyWidgetClient.java:603)
org.apache.jsp.index_jsp._jspService(index_jsp.java:67)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Observations:
I know I'm missing something as it required the default constructor to be present on the CompanyClient object, and it logs that it builds a CompanyClient object on deployment. I guess I'm not very clear on scope when it comes to Spring application context. My understanding was that a singleton bean should be available using the application context irrespective of the scope of the calling bean. Any and all help is very appreciated!
When you are instantiating the CompanyWidgetClient directly:
new CompanyWidgetClient(...)
you are not giving the spring DI container a chance to inject an instance of HeartbeatService - so its null.
When getting an instance of CompanyWidgetClient - retrieve the instance from Spring Applicaiton Context (via getBean() or similar) - so the HeartbeatService will have been Autowired.