i am building a small web application with spring boot and theirfore i do not have an xml files as all configurations are handled by spring boot capabilities , however i decided to add an xmlViewResolver and gave the first priority. With that said i keep getting the following error:
Please Assist me in anyway possible , thank you
Configuration file is as follows:
package com.aubrey.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.XmlViewResolver;
#Configuration
#ComponentScan
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver jspViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsps/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean(name = "messageSource")
public ReloadableResourceBundleMessageSource getMessageSource() {
ReloadableResourceBundleMessageSource resource = new ReloadableResourceBundleMessageSource();
resource.setBasename("classpath:messages");
resource.setDefaultEncoding("UTF-8");
return resource;
}
#Bean
public XmlViewResolver xmlViewResolver(){
XmlViewResolver resolver = new XmlViewResolver();
Resource resource = new ClassPathResource("/WEB-INF/Spring/views.xml");
resolver.setLocation(resource);
//xmlViewResolver().setOrder(1);
return resolver;
}
}
views.xml is as follows :
<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.xsd">
<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="welcome" class="org.springframework.web.servlet.view.JstlView">
<property name="url" value="/WEB-INF/views/xml_welcome.jsp" />
</bean>
</beans>
</beans>
Home controller is as follows:
package com.aubrey.demo.controllers;
import com.aubrey.demo.data.entities.Project;
import com.aubrey.demo.data.entities.Sponsor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HomeController {
#RequestMapping("/home")
public String goHome(Model model){
Project project = new Project();
project.setName("First Project");
project.setSponsor(new Sponsor("NASA", "555-555-5555", "nasa#nasa.com"));
project.setDescription("This is a simple project sponsored by NASA");
model.addAttribute("currentProject", project);
return "welcome";
}
}
Related
I am trying to create a maven project to access Oracle database with more than one datasource configurations. Here is my code:
First DataSource Config:
package com.business.data.datasource;
import javax.sql.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
#Configuration
public class FirstDbConfig {
#Primary
#Bean(name = "firstDataSourceProperties")
#ConfigurationProperties("first.datasource")
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
}
#Primary
#Bean(name = "firstDataSource")
#ConfigurationProperties(prefix = "first.datasource")
public DataSource dataSource(#Qualifier("firstDataSourceProperties") DataSourceProperties properties) {
return DataSourceBuilder.create().build();
}
#Bean(name = "firstSessionFactory")
#Primary
public SqlSessionFactoryBean firstSessionFactory(#Qualifier("firstDataSource") final DataSource firstDataSource)
throws Exception {
final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(firstDataSource);
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:./mapper/FirstDbMapper.xml"));
sqlSessionFactoryBean.setTypeAliasesPackage("com.business.data.model");
return sqlSessionFactoryBean;
}
}
Second DataSource Config:
package com.business.data.datasource;
import javax.sql.DataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
#Configuration
public class SecondDbConfig {
#Primary
#Bean(name = "secondDataSourceProperties")
#ConfigurationProperties("second.datasource")
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
}
#Bean(name = "secondDataSource")
#ConfigurationProperties(prefix = "second.datasource")
public DataSource dataSource(#Qualifier("secondDataSourceProperties") DataSourceProperties properties) {
return DataSourceBuilder.create().build();
}
#Bean(name = "secondSessionFactory")
public SqlSessionFactoryBean secondSessionFactory(#Qualifier("secondDataSource") final DataSource firstDataSource)
throws Exception {
final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(firstDataSource);
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:./mapper/SecondDbMapper.xml"));
sqlSessionFactoryBean.setTypeAliasesPackage("com.business.data.model");
return sqlSessionFactoryBean;
}
}
First Mapper interface:
package com.business.data.repository;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.business.data.model.PersonDetail;
import org.springframework.stereotype.Repository;
#Repository
#Mapper
public interface FirstDbMapper {
public List<PersonDetail> getUserData(#Param("firstName") String firstName, #Param("lastName") String lastName);
}
Second Mapper interface:
package com.business.data.repository;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.business.data.model.PersonDetail;
import org.springframework.stereotype.Repository;
#Repository
#Mapper
public interface SecondDbMapper {
public List<PersonDetail> getStaffData(#Param("firstName") String firstName, #Param("lastName") String lastName);
}
src/main/resources/mapper/FirstMapper.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace must indicate mapper interface full package path . It is an alias here-->
<mapper namespace = "com.business.data.repository.FirstDbMapper">
<select id = "getUserData" parameterType = "map" resultMap = "personDetailMap">
SELECT *
FROM user
WHERE UPPER(first_name) LIKE UPPER(#{firstName}||'%')
AND UPPER(last_name) LIKE UPPER(#{lastName}||'%')
</select>
...
</mapper>
src/main/resources/mapper/SecondMapper.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace must indicate mapper interface full package path . It is an alias here-->
<mapper namespace = "com.business.data.repository.SecondDbMapper">
<select id = "getStaffData" parameterType = "map" resultMap = "personDetailMap">
SELECT *
FROM staff
WHERE UPPER(first_name) LIKE UPPER(#{firstName}||'%')
AND UPPER(last_name) LIKE UPPER(#{lastName}||'%')
</select>
...
</mapper>
Service class is like
#Autowired
FirstDbMapper firstDbMapper;
public List<PersonDetail> getUser(String fName, String lName) throws MyServiceException {
...
try {
userList = firstDbMapper.getUserData(fName, lName);
} catch (Exception e) {
...
}
return userList;
}
application.properties:
first.datasource.jdbc-url=jdbc:oracle:thin:#host01:1561:db1
first.datasource.username=user1
first.datasource.password=password1
second.datasource.jdbc-url=jdbc:oracle:thin:#host02:1561:db2
second.datasource.username=user2
second.datasource.password=password2
I also have #MapperScan("com.business.data.repository") in my spring boot application java.
I can only make one datasource work, which is the one with #Primary annotation. I swapped #Primary between the two configuration, always the one with #Primary worked, the other got "Invalid bound statement (not found)" error.
Can anyone help me out?
Thanks!
You can use the #MapperScan annotation on a configuration class to attach mappers to the different session factories. I find it convenient to place mappers in different packages like this:
#MapperScan(basePackages="mapper.package1", sqlSessionFactoryRef="firstSessionFactory")
#MapperScan(basePackages="mapper.package2", sqlSessionFactoryRef="secondSessionFactory")
The issue was resolved by using HikariDataSource.
#Primary
#Bean(name = FIRST_DATASOURCE)
#ConfigurationProperties(prefix = "first.datasource")
public DataSource dataSourceFirst() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
This is my first experience using Spring MVC with REST API for having an angular front end. I created 3 configuration files:
Here is my ApplicationConfig
package com.app.config;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import javax.persistence.EntityManagerFactory;
#SuppressWarnings("unused")
#EnableWebMvc
#Configuration
#ComponentScan("com.app.controller")
#EnableJpaRepositories("com.app.dao")
public class ApplicationConfig {
#Bean
public InternalResourceViewResolver setup() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean
public DataSource dataSource() {
System.out.println("in datasoure");
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/db");
dataSource.setUsername("root");
dataSource.setPassword("");
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.app.model");
factory.setDataSource(dataSource());
return factory;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
}
MVC Config
package com.app.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#EnableWebMvc
#Configuration
public class MvcConfig implements WebMvcConfigurer {
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/views/", ".jsp");
}
#Bean
public InternalResourceViewResolver setup() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
WebInitializer
package com.app.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { ApplicationConfig.class, MvcConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
I also created a controller :
package com.app.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.app.dao.AdminsRepository;
import com.app.model.Admin;
#SuppressWarnings("unused")
#Controller
public class AdminsController {
#Autowired
private AdminsRepository adminsRepository;
#GetMapping("/admins")
#ResponseBody
public String getAllAdmins(Model model) {
return adminsRepository.findAll().toString();
}
#GetMapping("/admin/{id}")
#ResponseBody
public String getAdmin(#PathVariable("id") int id, Model model) {
return adminsRepository.findById((long) id).orElse(null).toString();
}
#PostMapping("/admin")
#ResponseBody
public String createAdmin(Admin admin, Model model) {
System.out.println(admin);
return adminsRepository.save(admin).toString();
}
}
The repository :
package com.app.dao;
//import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.app.model.Admin;
#Repository
public interface AdminsRepository extends JpaRepository <Admin, Long>{ }
And my model :
package com.app.model;
import java.io.Serializable;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.List;
#Entity
#Table(name="admins")
#NamedQuery(name="Admin.findAll", query="SELECT a FROM Admin a")
public class Admin implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int id;
#Column(name="created_at")
private Timestamp createdAt;
private String email;
private String login;
private String password;
private String name;
private String surname;
// ... getters and setters + delegated methods
}
When I start running the application and open the browser I receive an error message:
No qualifying bean of type 'com.app.dao.AdminsRepository' available:
expected at least 1 bean which qualifies as autowire candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
G'day David,
Just breaking down the answer moiljter already gave you.
You can only #Autowire objects that are declared in packages being scanned for components.
Currently, your #ComponentScan annotation only includes your controller package:
#ComponentScan("com.app.controller")
Broaden the search slightly like so:
#ComponentScan("com.app")
Then it should pick up your AdminsRepository and hum nicely.
Cheers,
ALS
You need to add "com.app.dao" to the list of packages that Spring will scan for components (and maybe also "com.app.model" if any of those annotations are Spring ones), or just change it to scan "com.app" (which will include everything in your app.
i'm trying to implement api documentation using swagger2 and springfox.
my project isn't a spring boot or maven , it depend on xml files.
i have added the class :
SwaggerConfig
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 springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
#EnableSwagger2
#PropertySource("classpath:swagger.properties")
#ComponentScan(basePackageClasses = ProductController.class)
#Configuration
public class SwaggerConfig {
private static final String SWAGGER_API_VERSION = "1.0";
private static final String LICENSE_TEXT = "License";
private static final String title = "Products REST API";
private static final String description = "RESTful API for Products";
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(title)
.description(description)
.license(LICENSE_TEXT)
.version(SWAGGER_API_VERSION)
.build();
}
#Bean
public Docket productsApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.pathMapping("/")
.select()
.paths(PathSelectors.regex( "/*"))
.build();
}
}
so when i run the tomcat server it run normally without errors but when i put the following link :
http://localhost:8080/swagger-ui.html
nothing happens.
am i missing some configuration or any suggestion please?
Thank you in advance.
problem is solved after adding these statements in my
spring-config.xml
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"></mvc:resources>
<mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"></mvc:resources>
<bean class="springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration" id="swagger2Config"/>
I am using Spring Boot with EhCache and Jersey, I am having issue to make BootstrapCacheLoader work, debug shows the load function executes and make call to the function (for which I want result to be cached). but once app is started the first request still calls the function and takes it's time to load data and then afterwords it is quick i.e. first call takes around 2 minutes and then following requests take less than a second.
here is my implementation:
ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="true"
monitoring="autodetect"
dynamicConfig="true">
<diskStore path="java.io.tmpdir" />
<cache name="idsMap"
maxEntriesLocalHeap="1000"
maxEntriesLocalDisk="10000"
eternal="true"
diskSpoolBufferSizeMB="20"
memoryStoreEvictionPolicy="LFU"
transactionalMode="off">
<persistence strategy="localTempSwap" />
</cache>
</ehcache>
EhCache Config
package com.spinners.rest.config;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheFactoryBean;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
/**
* #author sajid
*
*/
#Configuration
#EnableCaching
public class EhCacheConfig {
#Autowired
CacheManager cacheManager;
#Bean
public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
return ehCacheManagerFactoryBean;
}
#Bean
public CacheManager cacheManager() {
EhCacheCacheManager cacheManager = new EhCacheCacheManager();
cacheManager.setCacheManager(ehCacheManagerFactoryBean().getObject());
return cacheManager;
}
#Bean
public MyBootstrapCacheLoaderFactory myBootstrapCacheLoaderFactory() {
return new MyBootstrapCacheLoaderFactory();
}
#Bean
public EhCacheFactoryBean ehCacheFactory() {
EhCacheFactoryBean ehCacheFactory = new EhCacheFactoryBean();
ehCacheFactory.setCacheManager(ehCacheManagerFactoryBean().getObject());
ehCacheFactory.setBootstrapCacheLoader(myBootstrapCacheLoaderFactory());
return ehCacheFactory;
}
}
Here is my implementation of BootstrapCacheLoader
package com.spinners.rest.config;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import com.spinners.rest.repositories.IdsMapRepository;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.bootstrap.BootstrapCacheLoader;
import net.sf.ehcache.bootstrap.BootstrapCacheLoaderFactory;
public class MyBootstrapCacheLoaderFactory extends BootstrapCacheLoaderFactory implements BootstrapCacheLoader {
#Autowired
private IdsMapRepository idsMapRepo;
public MyBootstrapCacheLoaderFactory() {
super();
}
#Override
public BootstrapCacheLoader createBootstrapCacheLoader(Properties properties) {
return new MyBootstrapCacheLoaderFactory();
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public boolean isAsynchronous() {
return false;
}
public void load(Ehcache ehCache) throws CacheException {
try {
// function for which I want to load data in cache
Map<String, String> idsMap = idsMapRepo.getIdsMap();
} catch (Exception e) {
e.printStackTrace();
}
}
}
any suggestions? thanks in advance friends.
Best Regards
Sajid
I have this property-editor for my class Categoria and im trying to auto-wired it to the service, the problem its that the services keep getting a null value.
Also it seems like this is isolated or at least thats what i think, because i auto-wired a field of the same class at a controller, so i don't know whats going on, i already got an error like this, but at that time it didn't work at all .
Convertor
package com.carloscortina.paidosSimple.converter;
import java.beans.PropertyEditorSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.carloscortina.paidosSimple.model.Categoria;
import com.carloscortina.paidosSimple.service.CategoriaService;
public class CategoriaConverter extends PropertyEditorSupport{
private final Logger logger = LoggerFactory.getLogger(CategoriaConverter.class);
#Autowired
private CategoriaService categoriaService;
#Override
public void setAsText(String categoria) {
logger.info(categoria);
Categoria cat = new Categoria();
cat = categoriaService.getCategoria(Integer.parseInt(categoria));
setValue(cat);
}
}
Service
package com.carloscortina.paidosSimple.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.carloscortina.paidosSimple.dao.CategoriaDao;
import com.carloscortina.paidosSimple.model.Categoria;
#Service
#Transactional
public class CategoriaServiceImpl implements CategoriaService{
#Autowired
private CategoriaDao categoriaDao;
#Override
public Categoria getCategoria(int id) {
// TODO Auto-generated method stub
return categoriaDao.getCategoria(id);
}
#Override
public List<Categoria> getCategorias() {
return categoriaDao.getCategorias();
}
}
Here It does Work
Controller
package com.carloscortina.paidosSimple.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.carloscortina.paidosSimple.converter.CategoriaConverter;
import com.carloscortina.paidosSimple.model.Categoria;
import com.carloscortina.paidosSimple.model.Personal;
import com.carloscortina.paidosSimple.model.Usuario;
import com.carloscortina.paidosSimple.service.CategoriaService;
import com.carloscortina.paidosSimple.service.PersonalService;
import com.carloscortina.paidosSimple.service.UsuarioService;
#Controller
public class PersonalController {
private static final Logger logger = LoggerFactory.getLogger(PersonalController.class);
#Autowired
private PersonalService personalService;
#Autowired
private UsuarioService usuarioService;
#Autowired
private CategoriaService categoriaService;
#RequestMapping(value="/usuario/add")
public ModelAndView addUsuarioPage(){
ModelAndView modelAndView = new ModelAndView("add-usuario-form");
modelAndView.addObject("categorias",categorias());
modelAndView.addObject("user", new Usuario());
return modelAndView;
}
#RequestMapping(value="/usuario/add/process",method=RequestMethod.POST)
public ModelAndView addingUsuario(#ModelAttribute Usuario user){
ModelAndView modelAndView = new ModelAndView("add-personal-form");
usuarioService.addUsuario(user);
logger.info(modelAndView.toString());
String message= "Usuario Agregado Correctamente.";
modelAndView.addObject("message",message);
modelAndView.addObject("staff",new Personal());
return modelAndView;
}
#RequestMapping(value="/personal/list")
public ModelAndView listOfPersonal(){
ModelAndView modelAndView = new ModelAndView("list-of-personal");
List<Personal> staffMembers = personalService.getAllPersonal();
logger.info(staffMembers.get(0).getpNombre());
modelAndView.addObject("staffMembers",staffMembers);
return modelAndView;
}
#RequestMapping(value="/personal/edit/{id}",method=RequestMethod.GET)
public ModelAndView editPersonalPage(#PathVariable int id){
ModelAndView modelAndView = new ModelAndView("edit-personal-form");
Personal staff = personalService.getPersonal(id);
logger.info(staff.getpNombre());
modelAndView.addObject("staff",staff);
return modelAndView;
}
#RequestMapping(value="/personal/edit/{id}", method=RequestMethod.POST)
public ModelAndView edditingPersonal(#ModelAttribute Personal staff, #PathVariable int id) {
ModelAndView modelAndView = new ModelAndView("home");
personalService.updatePersonal(staff);
String message = "Personal was successfully edited.";
modelAndView.addObject("message", message);
return modelAndView;
}
#RequestMapping(value="/personal/delete/{id}", method=RequestMethod.GET)
public ModelAndView deletePersonal(#PathVariable int id) {
ModelAndView modelAndView = new ModelAndView("home");
personalService.deletePersonal(id);
String message = "Personal was successfully deleted.";
modelAndView.addObject("message", message);
return modelAndView;
}
private Map<String,String> categorias(){
List<Categoria> lista = categoriaService.getCategorias();
Map<String,String> categorias = new HashMap<String, String>();
for (Categoria categoria : lista) {
categorias.put(Integer.toString(categoria.getId()), categoria.getCategoria());
}
return categorias;
}
#InitBinder
public void initBinderAll(WebDataBinder binder){
binder.registerCustomEditor(Categoria.class, new CategoriaConverter());
}
}
DAO
package com.carloscortina.paidosSimple.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.carloscortina.paidosSimple.converter.CategoriaConverter;
import com.carloscortina.paidosSimple.model.Categoria;
#Repository
public class CategoriaDaoImp implements CategoriaDao {
private final Logger logger = LoggerFactory.getLogger(CategoriaConverter.class);
#Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
#Override
public Categoria getCategoria(int id) {
Categoria rol = (Categoria) getCurrentSession().get(Categoria.class, id);
if(rol == null) {
logger.debug("Null");
}else{
logger.debug("Not Null");
}
logger.info(rol.toString());
return rol;
}
#Override
#SuppressWarnings("unchecked")
public List<Categoria> getCategorias() {
// TODO Auto-generated method stub
return getCurrentSession().createQuery("from Categoria").list();
}
}
root-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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- Enable transaction Manager -->
<tx:annotation-driven/>
<!-- DataSource JNDI -->
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/paidos" resource-ref="true" />
<!-- Session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:hibernateProperties-ref="hibernateProperties"
p:packagesToScan="com.carloscortina.paidosSimple.model" />
<!-- Hibernate Properties -->
<util:properties id="hibernateProperties">
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5InnoDBDialect
</prop>
<prop key="hibernate.show_sql">false</prop>
</util:properties>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<context:annotation-config />
<context:component-scan base-package="com.carloscortina.paidosSimple,com.carlosocortina.paidosSimple.converter,com.carlosocortina.paidosSimple.service,com.carlosocortina.paidosSimple.dao" />
</beans>
Thanks in advance
Your are creating your PropertyEditor outside spring context using new operator (binder.registerCustomEditor(Categoria.class, new CategoriaConverter());) so service is not injected: follow the guide at this link to solve your problem.