Spring #Cacheable Not Working - spring

I have a dao method annotate with #Cacheable but its cache not working at all. I put log message inside the method.
<cache:annotation-driven mode="proxy" proxy-target-class="true" cache-manager="cacheManager" />
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="WEB-INF/ehcache/ehcache.xml"></property>
<property name="shared" value="true"></property>
</bean>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcache"></property>
</bean>
#Controller
#RequestMapping(value = "/analytics")
public class AnalyticsController {
#Autowired
private ReportDao reportDao;
/**
*
*/
public AnalyticsController() {
}
#RequestMapping(value = "/lcr-report", method = RequestMethod.GET)
public String viewCostReport(ModelMap map) {
List<Country> countryList = reportDao.getAllCountry();
map.put("countryList", countryList);
return "lcrReport";
}
}
#Repository
#Transactional(propagation=Propagation.REQUIRED, isolation=Isolation.DEFAULT,
rollbackFor={DataAccessException.class, SQLException.class, Exception.class})
public class ReportDao {
#Autowired
private JdbcTemplate dao;
/**
*
*/
public ReportDao() {
}
#Cacheable(value = {"reportDao"}/*, key= "T(Country).hash(#List<Country>)"*/)
#Transactional(propagation=Propagation.REQUIRED, isolation=Isolation.DEFAULT, readOnly=true,
rollbackFor={DataAccessException.class, SQLException.class, Exception.class})
public List<Country> getAllCountry() {
List<Country> countryList = null;
BeanPropertyRowMapper<Country> mapper = new BeanPropertyRowMapper<Country>(Country.class);
PreparedStatementCreator psc = new GenericPreparedStatementCreator("select c.country_code as countryCode, c.name as countryName from country c");
System.out.println("Not from cache");
countryList = dao.query(psc, mapper);
return countryList;
}
}

You should create key by using parameters to method getAllCountry. In your case it is empty, so you can do like this:
#Transactional(readOnly = true)
#Cacheable(value = CACHE_NAME, key = "'countries'")
and check if it works using Map cache:
#Configuration
#EnableCaching(proxyTargetClass = true)
public class CacheProducer {
#Bean
public CacheManager cacheManager() {
SimpleCacheManager result = new SimpleCacheManager();
result.setCaches(Arrays.asList(new ConcurrentMapCache(DictionaryServiceImpl.CACHE_NAME)));
return result;
}
}
If it works - it is time to check your echache config.

Related

Unable to autowire sessionfactory object in hibernate utility class,though i am getting it on controller

<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:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
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.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<context:property-placeholder location="classpath:application.properties" />
<mvc:annotation-driven />
<context:component-scan base-package="com.bizega.bzcrm" />
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
<!-- <bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10000000" />
</bean>-->
<!-- DataSource -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${hbm2ddl.auto}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
<property name="packagesToScan" value="com.bizega.bzcrm.hbmapping"></property>
</bean>
<bean id="hibernateUtil" class="com.bizega.bzcrm.util.HibernateUtil">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Transaction -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
this is my dispathureservlet.xml
<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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"/>
this is my aaplicationContext.xml
#Transactional
#Controller
public class EmployeeController {
#Autowired
private SessionFactory sessionFactory;
EmployeeService empService = new EmployeeService();
#RequestMapping(value = "/{menuid}", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<List<ModuleWrapper>> getModule(#PathVariable int menuid) throws Exception {
return new ResponseEntity<>(empService.getModule(), HttpStatus.OK);
}
#RequestMapping(value = "/save.lx", method = RequestMethod.POST)
public String createEmployee(#ModelAttribute EmployeeFormBean employee, ModelMap obj) {
Map map = new HashMap();
map.put("sf", sessionFactory);
Employee employee1 = new Employee();
employee1.setDesgid(employee.getDesigid());
employee1.setEmpcode(employee.getEmpcode());
employee1.setMobile(employee.getMobile());
employee1.setEmpname(employee.getName());
employee1.setAhid(1);
employee1.setDeptid(1);
employee1.setEmail(employee.getEmail());
employee1.setPhone(employee.getPhone());
employee1.setIsactive(1);
empService.saveEmployee(employee1, map);
List<Employee> employees = empService.findAllEmployees(map);
obj.addAttribute("employees", employees);
return "userlist";
}
#RequestMapping(value = "/deleteuser.lx", method = RequestMethod.GET)
public String deleteEmployee(#RequestParam("id") int id, ModelMap obj) {
Map map = new HashMap();
map.put("sf", sessionFactory);
empService.deleteEmployeeById(id, map);
List<Employee> employees = empService.findAllEmployees(map);
obj.addAttribute("employees", employees);
return "userlist";
}
#RequestMapping(value = "/edituser.lx", method = RequestMethod.GET)
public String updateEmployee(#RequestParam("id") int id, ModelMap obj) {
Map map = new HashMap();
map.put("sf", sessionFactory);
Employee emp = empService.findById(id, map);
obj.addAttribute("employee", emp);
return "updateEmp";
}
#RequestMapping(value = "/update.lx", method = RequestMethod.POST)
public String updateEmployeeDetails(#ModelAttribute Employee employee, ModelMap obj) {
Map map = new HashMap();
map.put("sf", sessionFactory);
empService.updateEmployee(employee, map);
List<Employee> employees = empService.findAllEmployees(map);
obj.addAttribute("employees", employees);
return "userlist";
}
#RequestMapping(value = "/listEmp.lx")
public String listEmployee(ModelMap obj) {
Map map = new HashMap();
map.put("sf", sessionFactory);
List<Employee> employees = empService.findAllEmployees(map);
obj.addAttribute("employees", employees);
return "userlist";
}
#RequestMapping(value = "/updateEmpField.lx")
public String updateSingleField(#RequestBody SingleField singleField) {
Map map = new HashMap();
map.put("sf", sessionFactory);
empService.updateEmpField(singleField,map);
// obj.addAttribute("employees", employees);
return "userlist";
}
}
this is my controller
#Transactional
#Service("empService")
public class EmployeeService {
#Autowired
SessionFactory sessionFactory;
EmployeeDataManager datamanager = new EmployeeDataManager();
public List<ModuleWrapper> getModule() throws Exception {
return datamanager.getModule();
}
#Transactional
public void saveEmployee(Employee employee, Map map) {
datamanager.saveEmployee(employee, map);
}
public List<Employee> findAllEmployees(Map map) {
return datamanager.findAllEmployees(map);
}
public void deleteEmployeeById(int id, Map map) {
datamanager.deleteEmployeeById(id, map);
}
public Employee findById(int id, Map map) {
return datamanager.findById(id, map);
}
public void updateEmployee(Employee employee, Map map) {
datamanager.updateEmployee(employee, map);
}
public void updateEmpField(SingleField singleField,Map map)
{
datamanager.updateEmpField(singleField,map);
}
}
this is my service
#Transactional
#Component
public class EmployeeDataManager extends HibernateUtil {
private HibernateUtil hbutil;
#Autowired
SessionFactory sessionFactory;
public void saveEmployee(final Employee employee, Map map) {
hbutil = new HibernateUtil();
hbutil.save(employee, map);
}
public List<Employee> findAllEmployees(Map map) {
hbutil = new HibernateUtil();
hbutil.test();
return hbutil.getAll(Employee.class, map);
}
public void deleteEmployeeById(int id, Map map) {
SessionFactory sessionFactory = (SessionFactory) map.get("sf");
Employee employee = hbutil.get(Employee.class, id, map);
hbutil.setSessionFactory(sessionFactory);
hbutil.delete(employee, map);
}
public Employee findById(int id, Map map) {
hbutil = new HibernateUtil();
Employee employee = hbutil.get(Employee.class, id, map);
return employee;
}
public void updateEmployee(Employee employee, Map map) {
hbutil = new HibernateUtil();
Employee e1 = hbutil.get(Employee.class, employee.getEmpid(), map);
e1.setEmpname(employee.getEmpname());
e1.setDesgid(employee.getDesgid());
e1.setEmail(employee.getEmail());
e1.setEmpcode(employee.getEmpcode());
e1.setMobile(employee.getMobile());
e1.setPhone(employee.getPhone());
// e1.setEmail(employee.getEmail());
hbutil.saveOrUpdate(e1);
}
}
this is my data manager
#Transactional
#Component
public class HibernateUtil {
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public <T> T save(final T o, Map map) {
sessionFactory = (SessionFactory) map.get("sf");
return (T) sessionFactory.getCurrentSession().save(o);
}
public void delete(final Object object, Map map) {
sessionFactory = (SessionFactory) map.get("sf");
sessionFactory.getCurrentSession().delete(object);
}
/**
*
* #param <T>
* #param type
* #param id
* #param map
* #return
*/
public <T> T get(final Class<T> type, final int id, Map map) {
sessionFactory = (SessionFactory) map.get("sf");
return (T) sessionFactory.getCurrentSession().get(type, id);
}
public <T> T merge(final T o) {
return (T) sessionFactory.getCurrentSession().merge(o);
}
/**
*
*
* #param <T>
* #param o
*/
public <T> void saveOrUpdate(final T o) {
sessionFactory.getCurrentSession().saveOrUpdate(o);
}
public <T> List<T> getAll(final Class<T> type, Map map) {
sessionFactory = (SessionFactory) map.get("sf");
final Session session = sessionFactory.getCurrentSession();
final Criteria crit = session.createCriteria(type);
return crit.list();
}
public <T> void updateSingleField(final Class<T> type, SingleField singleField, Map map) {
sessionFactory = (SessionFactory) map.get("sf");
final Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("update " + type.getSimpleName() + " set " + singleField.getColName() + "=:newValue where id=:id");
query.setParameter("newValue", singleField.getNewValue());
query.setParameter("id", singleField.getId());
int result = query.executeUpdate();
}
public void test() {
System.out.println("dfdfds " + sessionFactory);
throw new UnsupportedOperationException("Not supported yet.");
}
}
this is my hibernateUtil class
I am getting sessionfactory object at controller but not getting it in my datamanager and hibernate util so i have topass it using map
i am totally new to spring so please help me to solve this problem where i am wrong if you want any other details let me know
thanks in advance
To get bean with autowired fields you have to get it from applicationcontext, e.g. autowiring it. Spring is not so magical to inject beans to you object created by yourself with just "new Myobject()"

UsernameTokenValidator Can not #Autowired Dao

I have a Spring-ws and i am using Apahce-wss4j for spring-ws authentication. I want to use my Dao class in my custom TokenValidator class. But there was an exception can not #Autowired my Dao class. Here is my code
applicationContext.xml
<bean id="myWssConfig" class="tr.com.xxx.services.MyWssConfig"/>
<bean id="kepDBDAO" class="tr.com.xxx.dao.KepDBDAOImpl"/>
<bean id="ssha" class="tr.com.xxx.utils.SSHA"/>
<bean id="memberStatusService" class="tr.com.xxx.services.MemberStatusServiceImpl"/>
<bean id="myUsernameTokenValidator" class="tr.com.xxx.services.MyUsernameTokenValidator">
<property name="kepDBDAO" ref="kepDBDAO"/>
</bean>
<sws:interceptors>
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="UsernameToken"/>
<property name="validationCallbackHandler" ref="callbackHandler"/>
<property name="wssConfig">
<ref bean="myWssConfig"/>
</property>
</bean>
</sws:interceptors>
Here is MyWssConfig.java
#Component("myWssConfig")
public class MyWssConfig extends WSSConfig {
public MyWssConfig() {
setValidator(WSSecurityEngine.USERNAME_TOKEN, MyUsernameTokenValidator.class);
setRequiredPasswordType(WSConstants.PASSWORD_TEXT);
}
}
And here is MyUsernameTokenValidator.java
#Component
public class MyUsernameTokenValidator extends UsernameTokenValidator {
private static final Logger LOGGER = LoggerFactory
.getLogger(MyUsernameTokenValidator.class);
#Autowired
private KepDBDAO kepDBDAO;
#Transactional
protected void verifyPlaintextPassword(UsernameToken usernameToken, RequestData data) throws WSSecurityException {
if (usernameToken != null && usernameToken.getPassword() != null) {
byte[] saltValue = null;
kepDBDAO.getWsUsers("basvuru");
String hashPassword = null;
try {
hashPassword = SSHA.calculateSSHA256(saltValue, usernameToken.getPassword());
} catch (NoSuchAlgorithmException e) {
LOGGER.error(e.toString(), e);
} catch (IOException e) {
LOGGER.error(e.toString(), e);
}
usernameToken.setPassword(hashPassword);
super.verifyDigestPassword(usernameToken, data);
}
}
public KepDBDAO getKepDBDAO() {
return kepDBDAO;
}
public void setKepDBDAO(KepDBDAO kepDBDAO) {
this.kepDBDAO = kepDBDAO;
}
}
Couldn't #Autowired my KepDBDAO when I call webservice in SOAPUI.
Help me please.. THank you all guys.
Try this:
1. In applicationContext:
<context:component-scan base-package="tr.com.xxx.dao"/>
<context:component-scan base-package="package for MyUsernameTokenValidator"/>
remove these beans:
kepDBDAO, myUsernameTokenValidator
2. Remove setter and getter for KepDBDAO in MyUsernameTokenValidator
3. Make sure KepDBDAOImpl is marked as #Service
I solved my problem.
#Component("myWssConfig")
public class MyWssConfig extends WSSConfig {
#Autowired
private MyUsernameTokenValidator myUsernameTokenValidator;
//
#PostConstruct
public void myInit() {
setValidator(WSSecurityEngine.USERNAME_TOKEN, myUsernameTokenValidator);
setRequiredPasswordType(WSConstants.PASSWORD_TEXT);
}
}

Spring Social + Spring Security HTTPS/HTTP

How can I make the remember me cookie and session accessible through http when requesting a facebook login from either http or https with spring social. Currently if a user logs in through https the cookie is not readable through http pages (no user logged in). I am using use-secure-cookie="false" but that doesn't help.
<s:remember-me key="mykey" services-ref="rememberMeServices" use-secure-cookie="false"/>
<bean id="rememberMeServices" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
<property name="userDetailsService" ref="userService" />
<property name="tokenRepository" ref="persistentTokenRepository" />
<property name="key" value="mykey" />
<property name="cookieName" value="rmb" />
<property name="useSecureCookie" value="false" />
<property name="tokenValiditySeconds" value="946708560" />
<property name="alwaysRemember" value="true"></property>
</bean>
My Social Config:
#Configuration
public class SocialConfig {
#Inject
private Environment environment;
#Inject
private DataSource dataSource;
#Inject
private TextEncryptor textEncryptor;
#Value("${app.url}")
private String applicationUrl;
#Value("${facebook.clientId}")
private String facebookClientId;
#Value("${facebook.clientSecret}")
private String facebookClientSecret;
#Bean
public ConnectionFactoryLocator connectionFactoryLocator() {
ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
registry.addConnectionFactory(new FacebookConnectionFactory(
facebookClientId,
facebookClientSecret));
return registry;
}
#Bean
#Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public ConnectionRepository connectionRepository() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
}
return usersConnectionRepository().createConnectionRepository(authentication.getName());
}
#Bean
public UsersConnectionRepository usersConnectionRepository() {
JdbcUsersConnectionRepository repository = new JdbcUsersConnectionRepository(
dataSource, connectionFactoryLocator(), textEncryptor);
repository.setConnectionSignUp(connectionSignUp());
return repository;
}
#Bean
public TextEncryptor textEncryptor() {
return Encryptors.noOpText();
}
#Bean
public ConnectController connectController() {
ConnectController controller = new ConnectController(
connectionFactoryLocator(), connectionRepository());
controller.setApplicationUrl(applicationUrl);
return controller;
}
#Bean
public ProviderSignInController providerSignInController(RequestCache requestCache) {
ProviderSignInController controller = new ProviderSignInController(connectionFactoryLocator(),
usersConnectionRepository(), signInAdapter());
controller.setSignUpUrl("/register");
controller.setSignInUrl("/socialSignIn");
controller.setPostSignInUrl("socialSignIn");
controller.addSignInInterceptor(new RedirectAfterConnectInterceptor());
return controller;
}
#Bean
public SignInAdapter signInAdapter() {
return new SignInAdapterImpl();
}
#Bean
public ConnectionSignUp connectionSignUp() {
return new ConnectionSignUpImpl();
}
}

Getting jdbcTemplate null in Spring Junit test case

I am writing junit test case for spring 3 restful services. When I am trying to execute it as junit, i am getting JdbcTemplate as null. I am not sure where I did the mistake. Please help me to get out of this...
LoginServiceImpl.java file,
private NamedParameterJdbcTemplate jdbcTemplate;
#Autowired
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
System.out.println("--------------"+jdbcTemplate.toString());
}
private static Map<String, AuthToken> tokenHash = new ConcurrentHashMap<String, AuthToken>();
private static String authTokenDetailsSql = "select * from authtoken where token = :token";
#Override
#RequestMapping(value = "/register", method = RequestMethod.POST)
#ResponseBody
public ServiceBean newAccount(#RequestBody Registration registration) {
String newAccountSql = "INSERT INTO account (email,password,name) VALUES (:email,:password,:name)";
ServiceDataBean<AuthToken> retBean = new ServiceDataBean<AuthToken>();
try {
System.out.println("register service calling.....");
MapSqlParameterSource namedParameters = new MapSqlParameterSource();
namedParameters.addValue("email", registration.getEmail());
messageDigest = MessageDigest.getInstance("MD5");
byte[] md5 = new byte[64];
messageDigest.update(registration.getPassword().getBytes("iso-8859-1"), 0, registration.getPassword().length());
md5 = messageDigest.digest();
namedParameters.addValue("password", convertedToHex(md5));
namedParameters.addValue("name", registration.getName());
GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
// TODO what to do with the updInt also check it's not -1
int updInt = jdbcTemplate.update(newAccountSql, namedParameters, generatedKeyHolder);
long accountId = (Long) generatedKeyHolder.getKeys().get("GENERATED_KEY");
registration.getDevice().setOwner(registration.getId());
fotoframz.register(registration.getDevice());
Login login = new Login();
login.setEmail(registration.getEmail());
login.setPassword(registration.getPassword());
login.setDevice(registration.getDevice());
retBean = (ServiceDataBean<AuthToken>) this.login(login);
System.out.println("form register");
} catch (Throwable e) {
retBean.setStatusCode("001");
e.printStackTrace();
}
return retBean;
}
I am getting jdbctemplate=null at int updInt = jdbcTemplate.update(newAccountSql, namedParameters, generatedKeyHolder);
my applicationContext-test.xml file is in src/test/resources folder..applicationContext-test.xml file
<context:component-scan base-package="net.mss.ff.services" />
<context:property-placeholder location="classpath:/app.properties" />
<!-- <task:annotation-driven /> -->
<context:annotation-config />
<!-- <import resource="apicontroller_v1-servlet.xml"/>
<import resource="applicationContext.xml"/> -->
<bean id="photoService" class="net.mss.ff.services.core.api.impl.PhotoServiceImpl">
<property name="rootStorageFolder" value="${storage.root}" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
LoginServiceImplTest
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:/applicationContext-test.xml"})
public class LoginServiceImplTest {
LoginServiceImpl loginServiceObj = new LoginServiceImpl();
Device deviceMock;
#Autowired
private Fotoframz fotoframz;
/*private NamedParameterJdbcTemplate jdbcTemplate;
#Autowired
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}*/
#Before
public void setUp() throws Exception {
//loginServiceObj = new LoginServiceImpl();
}
#After
public void tearDown() throws Exception{
}
/**
* Test method for {#link net.mss.ff.services.core.api.impl.LoginServiceImpl#newAccount(net.mss.ff.services.core.beans.Registration)}.
*/
#Test
public void testNewAccount() {
Registration mockRegObj = new Registration();
deviceMock = new Device();
deviceMock.setActive(false);
deviceMock.setHeight(45);
//deviceMock.setId(4568);
deviceMock.setName("Android");
deviceMock.setOwner(1111);
deviceMock.setPlatform("Windows NT");
deviceMock.setUuid("522601");
deviceMock.setVersion("1.0");
deviceMock.setWidth(76);
mockRegObj.setEmail("bbb#gmail.com");
/*mockRegObj.setId(399);*/
mockRegObj.setName("bbb");
mockRegObj.setPassword("BBB");
mockRegObj.setDevice(deviceMock);
loginServiceObj.newAccount(mockRegObj);
//assertEquals("New Account Creation", "", "");
}
}
anything needs to modify in test class, please let me know..
In your test the LoginServiceImpl loginServiceObj = new LoginServiceImpl();
is not instantiated by spring, thus no annaotions will be applied. You need to autowire it, or inject it some other way. Spring 3.2 makes this kinda thing super easy and nice to use.
The rest of my answer is still good adivce :
You have not declared or instantiated the jdbctemplate in your java code. And you have not defined it in your xml file.
You need this
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref bean="dateSource"/>
</property>
</bean>
and then this as instance variable (assuming your using annoations)
#Resource(name = "jdbcTemplate")
private JdbcTemplate jdbcTemplate;
As #NimChimpsky mentioned you need to define your jdbcTemplate in your bean xml file and then in your instance variable you can also do.
#Autowired
private JdbcTemplate jdbcTemplate;

How to change XML-based Configuration to annotation configuration in Spring?

The class is as following:
class ReportControllerBase {
String reportName = "Report";
public String getReportName() {
return reportName;
}
public void setReportName(String reportName) {
this.reportName = reportName;
}
// ...
}
class AnnualReportController extends ReportControllerBase {
// ...
}
class SkinCareAnnualReprotController extends AnnualReportController {
String productName;
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
}
And the XML-based configuration is as following:
<bean id="annualReportController" class="AnnualReportController">
<property name="reportName" value="Annual Report"/>
</bean>
<bean id="annualSpecialReportController" class="AnnualReportController">
<property name="reportName" value="Annual Special Report"/>
</bean>
<bean id="skinCareAnnualReprotController" class="SkinCareAnnualReprotController" parent="annualReportController">
<property name="productName" value="A famous skin care product"/>
</bean>
The Bean annualReportController and annualSpecialReportController is the instance of the same Class. And skinCareAnnualReprotController is inherited from bean annualReportController.
How to implement this configuration in annotation-based configuration in Spring?
#Configuration
public class ReportConfiguration {
#Bean public AnnualReportController annualReportController() {
AnnualReportController annualReportController = new AnnualReportController();
annualReportController.setReportName("Annual Report");
return annualReportController;
}
#Bean public AnnualReportController annualSpecialReportController() {
AnnualReportController annualSpecialReportController = new AnnualReportController();
return withAnnualSpecialReportName(annualSpecialReportController);
}
#Bean public SkinCareAnnualReportController skinCareAnnualReportController() {
SkinCareAnnualReportController skinCareAnnualReportController = new SkinCareAnnualReportController();
skinCareAnnualReportController.setProductName("A famous skin care product");
return withAnnualSpecialReportName(skinCareAnnualReportController);
}
// in this instance, a helper method is arguably overkill,
// but I've included it for demonstration
private <T extends AnnualReportController> T withAnnualSpecialReportName(T report) {
report.setReportName("Annual Special Report");
return report;
}
}
Take a look at the Spring 3.1 documentation for more information.

Resources