I am learning to write a UnitTest for my JSF project which has ManangedBeans and Session Beans
I have a problem invoking the EJB from Mockito test
package Test;
import ejb.CountrySession;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
#Named(value = "countryMB")
#ViewScoped
public class CountryMB implements Serializable {
#EJB
private CountrySession countSession;
//
private String countryName;
//
private StatusMsg msg;
public CountryMB() {
}
public void setMsg(StatusMsg msg) {
this.msg = msg;
}
public void setCountSession(CountrySession countSession) {
this.countSession = countSession;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public void ajaxAll() {
}
public void saveCountry() {
if (countryName != null && !countryName.trim().isEmpty()) {
boolean chk = countSession.chkCountry(countryName);
if (!chk) {
chk = countSession.addCountry(countryName);
if (chk) {
msg.addInfo("Add Country", "New Country added");
} else {
msg.addError("Add Country", "Unable to add Country");
}
} else {
msg.addWarn("Add Country", "Country already exists");
}
} else {
msg.addWarn("Add Country", "Required parameter not available");
}
}
}
Now in my Test Code i have the following
package Test;
import ejb.CountrySession;
import entities.Country;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class CountryMBTest {
#Mock
private CountryMB countryMB;
#Mock
private StatusMsg sm;
#Mock
private CountrySession countSession;
#Mock
private EntityManager em;
#Mock
private Query qry;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
countryMB = new CountryMB();
countryMB.setMsg(sm);
countryMB.setCountSession(countSession);
}
#After
public void after() {
countryMB = null;
}
#Test
public void infoCountrySave() {
countryMB.setCountryName("Test");
countryMB.saveCountry();
verify(sm).addInfo("Add Country", "New Country added");
}
#Test
public void errorCountrySave() {
countryMB.setCountryName("Test");
countryMB.saveCountry();
verify(sm).addError("Add Country", "Unable to add Country");
}
#Test
public void warnCountrySave() {
countryMB.setCountryName("Test");
countryMB.saveCountry();
verify(sm).addWarn("Add Country", "Country already exists");
}
#Test
public void chkCountSave() {
List<Country> countLst = null;
Country dum = mock(Country.class);
EntityManager em = mock(EntityManager.class);
Mockito.when(em.find(Country.class, 111)).thenReturn(dum);
CountrySession cs = Mockito.mock(CountrySession.class);
Mockito.when(cs.chkCountry("Test")).thenCallRealMethod();
Mockito.when(cs.getEm()).thenReturn(em);
String name = "Test";
Assert.assertNull(cs.chkCountry(name));
}
}
My table has only one Record pk=1, Country=Test
The above test code never check the session beans, it just throw
java.lang.NullPointerException
at ejb.CountrySession.chkCountry(CountrySession.java:67)
at Test.CountryMBTest.chkCountSave(CountryMBTest.java:112)
And for infoCountrySave() & warnCountrySave() it just never check the supplied value in the database.
As i have never used any UnitTest earlier so i really don't know if what i am doing is correct, moreover i could not figure out any working code by googling.
It will be of great help if anyone can guide me to some resource available online or even let me know what is that i need to correct to get the above mockito test work with the ejb part.
Change #Mock with #InjectMocks for
private CountryMB countryMB
and when you get java.lang.NullPointerException. Mostly you miss inject some class or some dependency on by called when
Related
I have a CustomerUserDetailsService class, which is part of an implementation of Spring Boot authentication. I have tested my code manually, and it works correctly, allowing me to successfully log in to my app. However, I am unable to work out how to test the CustomerUserDetailsService.
As a unit test, I believe I would need to mock the userRepository member variable, but whatever I try in my test fails, the reason being userRepository is set to null. I've tried adding the #Repository annotation to userRepository but am told that is not allowed because it is an interface. There's also the fact that loadUserByUsername returns an instance of CustomUserDetails, which is just an implementation of an interface, so I have no idea how I'd mock that dependency?
I've also tried doing some kind of integration test but had similar issues, probably due to incorrect annotations on the test itself. In an ideal world, I'd prefer a unit test and would be extremely grateful for any guidance as to how to set it up.
These are the relevant classes...
CustomerUserDetailsService:
package com.phil.urlshortener.security;
import com.phil.urlshortener.model.User;
import com.phil.urlshortener.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
public class CustomUserDetailsService implements UserDetailsService {
#Autowired private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
return new CustomUserDetails(user);
}
}
User:
package com.phil.urlshortener.model;
import lombok.Data;
import javax.persistence.*;
#Data
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(nullable = false, unique = true, length = 50)
private String username;
#Column(nullable = false, length = 64)
private String password;
}
UserRepository:
package com.phil.urlshortener.repositories;
import com.phil.urlshortener.model.User;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<User, Long> {
#Query("SELECT u FROM User u WHERE u.username = ?1")
User findByUsername(String username);
}
CustomUserDetails:
package com.phil.urlshortener.security;
import com.phil.urlshortener.model.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
public class CustomUserDetails implements UserDetails {
private final User user;
public CustomUserDetails(User user) {
this.user = user;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
#Override
public String getPassword() {
return user.getPassword();
}
#Override
public String getUsername() {
return user.getUsername();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
Maybe you forgot to use mockito annotation #RunWith(MockitoJUnitRunner.class).
Here it's the unit test for CustomUserDetailsService :
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
#RunWith(MockitoJUnitRunner.class)
public class CustomUserDetailsService {
#Mock
private UserRepository userRepository;
private CustomUserDetailsService customUserDetailsService;
#Before
public void setUp() throws Exception {
customUserDetailsService = new CustomUserDetailsService(userRepository);
}
#Test
public void GIVEN_username_THEN_return_user_details() {
//Arrange
final String username = "existingUserName";
final User user = mock(User.class);
when(userRepository.findByUsername(username)).thenReturn(user);
//Act
final UserDetails userDetails = customUserDetailsService.loadUserByUsername(username);
//Assert
assertNotNull(userDetails);
assertEquals(user, ReflectionTestUtils.getField(userDetails, "user"));
}
}
I have abstract user service where I autowired two beans: Repository and AbstractMapper, but when I run test for that class, all faild with NullPointerException. When I run, for example, save test for that service in dubug, it show me that both beans are null. Anybody had this problem? This is my code:
AbstractService
package com.example.shop.service;
import com.example.shop.dto.AbstractMapper;
import com.example.shop.entity.Identifable;
import com.example.shop.repository.IRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
#Service`enter code here`
public abstract class AbstractService<E extends Identifable, D> implements IService<E, D> {
private IRepository<E> repository;
private AbstractMapper<E, D> abstractMapper;
#Autowired
public AbstractService(IRepository<E> repository, AbstractMapper<E, D> abstractMapper) {
this.repository = repository;
this.abstractMapper = abstractMapper;
}
#Override
public D get(Long id) {
E e = repository.get(id);
return abstractMapper.entityToDto(e);
}
#Override
public List<D> getAll() {
List<E> all = repository.getAll();
List<D> allDtos = all.stream()
.map(e -> abstractMapper.entityToDto(e))
.collect(Collectors.toList());
return allDtos;
}
#Override
public E save(D d) {
E e = abstractMapper.dtoToEntity(d);
return repository.save(e);
}
#Override
public E update(D d) {
E e = abstractMapper.dtoToEntity(d);
return repository.update(e);
}
#Override
public E delete(D d) {
E e = abstractMapper.dtoToEntity(d);
return repository.delete(e);
}
#Override
public void deleteAll() {
repository.deleteAll();
}
}
UserServiceImpl
package com.example.shop.service;
import com.example.shop.dto.UserDto;
import com.example.shop.dto.UserMapper;
import com.example.shop.entity.User;
import com.example.shop.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class UserServiceImpl extends AbstractService<User, UserDto> implements UserService {
private UserRepository repository;
private UserMapper userMapper;
#Autowired
public UserServiceImpl(UserRepository repository, UserMapper userMapper) {
super(repository, userMapper);
}
}
Abstract Mapper
package com.example.shop.dto;
import org.springframework.stereotype.Component;
#Component
public interface AbstractMapper<E, D> {
E dtoToEntity(D d);
D entityToDto(E e);
}
User Mapper:
package com.example.shop.dto;
import com.example.shop.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class UserMapper implements AbstractMapper<User, UserDto> {
private AccountMapper accountMapper;
#Autowired
public UserMapper(AccountMapper accountMapper) {
this.accountMapper = accountMapper;
}
#Override
public User dtoToEntity(UserDto dto) {
if (dto == null) {
return null;
}
User user = new User();
user.setId(dto.getId());
user.setEmail(dto.getEmail());
user.setPassword(dto.getPassword());
user.setLogin(dto.getLogin());
user.setAccount(accountMapper.dtoToEntity(dto.getAccountDto()));
return user;
}
#Override
public UserDto entityToDto(User user) {
if (user == null) {
return null;
}
UserDto dto = new UserDto();
dto.setEmail(user.getEmail());
dto.setLogin(user.getLogin());
dto.setPassword(user.getPassword());
dto.setId(user.getId());
dto.setAccountDto(accountMapper.entityToDto(user.getAccount()));
return dto;
}
}
Class with #SpringBootApplication
package com.example.shop;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ShopApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("Test");
}
}
And my tests for Service:
package com.example.shop.service;
import com.example.shop.dto.UserDto;
import com.example.shop.entity.User;
import com.example.shop.repository.IRepository;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.mockito.Mockito.*;
#RunWith(SpringRunner.class)
#SpringBootTest
public class UserServiceImplTest {
private static final Long VALID_ID = 1L;
#Mock
private IRepository<User> repository;
#InjectMocks
private UserServiceImpl service;
#After
public void tearDown() {
repository.deleteAll();
}
#Test
public void get() {
service.get(VALID_ID);
verify(repository, times(1)).get(anyLong());
}
#Test
public void save() {
UserDto dto = createUser();
service.save(dto);
verify(repository, times(1)).save(any());
}
#Test
public void getAll() {
service.getAll();
verify(repository, times(1)).getAll();
}
#Test
public void update() {
UserDto dto = createUser();
service.update(dto);
verify(repository, times(1)).update(any());
}
#Test
public void delete() {
UserDto dto = createUser();
service.delete(dto);
verify(repository, times(1)).delete(any());
}
#Test
public void deleteAll() {
service.deleteAll();
verify(repository, times(1)).deleteAll();
}
private UserDto createUser() {
return new UserDto();
}
}
There are several problems with this code. First of all you do not need to annotate the abstract classes with service or component. Abstract classes cannot be instantiated, therefore there is no bean.
Second: autowire of classes having generics wont work. As soon as you have several bean, it wont be unique anymore.
Checkout if your classes get instantiated. Maybe you need to add #componentscan.
Your test is located under: com.example.shop.service and therefore it only scans the beans under this package. You should either move your test or add the beans by using the componentscan annotation
I am a new beginner in Spring boot...I encounter a problem When I run my controller,
Description:
Field todoService in com.springboot.todoController.TodoController
required a bean of type 'com.springboot.todo.TodoService' that could
not be found.
Action:
Consider defining a bean of type 'com.springboot.todo.TodoService' in
your configuration.
below is my code
Todo.java
package com.springboot.todoBean;
import java.util.Date;
public class Todo {
private int id;
private String user;
private String desc;
private Date targetDate;
private boolean isDone;
public Todo() {}
public Todo(int id, String user, String desc, Date targetDate, boolean isDone) {
super();
this.id = id;
this.user = user;
this.desc = desc;
this.targetDate = targetDate;
this.isDone = isDone;
}
public int getId() {
return id;
}
public String getUser() {
return user;
}
public String getDesc() {
return desc;
}
public Date getTargetDate() {
return targetDate;
}
public boolean isDone() {
return isDone;
}
}
TodoService.java
package com.springboot.todo;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Service;
import com.springboot.todoBean.Todo;
#Service
public class TodoService {
private static List<Todo> todos = new ArrayList<Todo>();
private static int todoCount = 3;
static {
todos.add(new Todo(1, "Jack", "Learn Spring MVC", new Date(), false));
todos.add(new Todo(2, "Jack", "Learn Struts", new Date(), false));
todos.add(new Todo(3, "Jill", "Learn hibernate", new Date(), false));
}
public List<Todo> retrieveTodos(String user){
List<Todo> filteredTodos = new ArrayList<Todo>();
for (Todo todo : todos) {
if(todo.getUser().equals(user))
filteredTodos.add(todo);
}
return filteredTodos;
}
public Todo addTodo(String name, String desc,
Date targetDate, boolean isDone) {
Todo todo = new Todo(++todoCount, name, desc, targetDate, isDone);
todos.add(todo);
return todo;
}
public Todo retrievedTodo(int id) {
for(Todo todo: todos) {
if(todo.getId() == id)
return todo;
}
return null;
}
}
TodoController.java
package com.springboot.todoController;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.springboot.todo.TodoService;
import com.springboot.todoBean.Todo;
#RestController
public class TodoController {
#Autowired
private TodoService todoService;
#GetMapping("/users/{name}/todos")
public List<Todo> retrieveTodo(#PathVariable String name){
return todoService.retrieveTodos(name);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(TodoController.class, args);
}
}
I have added the annotation #Service to the TodoService to tell spring boot it is a bean, but it still cannot recognise, could anyone tell me how to solve this problem? thanks
Create a separate class as below for start the spring boot application. Also, please note that below class should be placed in higher level in the package hierarchy than other controller, service, etc classes.
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Your error is generated because your application is not scanning TodoService.
The mentioned code has several problems:
please make all packages lower case - java convention
please move the main in another class and annotate it with #SpringBootApplication
ex.
#SpringBootApplication
public class Application{
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
3. by default the spring boot application will scan beans contained in the package where the class from 2 is defined. You can put the class from 2 in the common package for both service and controller.
I have web written in Spring. I use Hibernate for JPA. I need to find entity in database, I get ID from user.
Problem is if ID is not in database - I get a NullPointerException.
Now I have:
People p;
try {
p = peopleManager.findById(id);
if (p != null) {
model.addAttribute("message", "user exist, do any action");
} else {
model.addAttribute("message", "user NOT exist");
}
} catch (NullPointerException e) {
model.addAttribute("message", "user NOT exist");
}
but it looks terrible. How can I do it right?
There is complete example code:
package com.example.test.entity;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class People {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name="name")
private String name;
#Column(name="age")
private int age;
}
/* ---------------------------------------------------- */
package com.example.test.dao;
import java.util.List;
import com.example.test.entity.People;
public interface PeopleDao {
public void save(People people);
public void delete(People people);
public void update(People people);
public List<People> findAll();
public People findById(int id);
}
/* ---------------------------------------------------- */
package com.example.test.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.example.test.entity.People;
#Repository
public class PeopleDaoImpl implements PeopleDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public void save(People people) {
this.sessionFactory.getCurrentSession().save(people);
}
#Override
public void delete(People people) {
this.sessionFactory.getCurrentSession().delete(people);
}
#Override
public void update(People people) {
this.sessionFactory.getCurrentSession().update(people);
}
#Override
public List<People> findAll() {
return this.sessionFactory.getCurrentSession().createQuery("from People ORDER BY age").list();
}
#Override
public People findById(int id) {
return (People) this.sessionFactory.getCurrentSession().get(People.class, id);
}
}
/* ---------------------------------------------------- */
package com.example.test.service;
import java.util.List;
import com.example.test.entity.People;
public interface PeopleManager {
public void save(People people);
public void delete(People people);
public void update(People people);
public List<People> findAll();
public People findById(int id);
}
/* ---------------------------------------------------- */
package com.example.test.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.example.test.dao.PeopleDao;
import com.example.test.entity.People;
#Service
#Transactional
public class PeopleManagerImpl implements PeopleManager {
#Autowired
private PeopleDao peopleDao;
#Override
public void save(People people) {
peopleDao.save(people);
}
#Override
public void delete(People people) {
peopleDao.delete(people);
}
#Override
public void update(People people) {
peopleDao.update(people);
}
#Override
public List<People> findAll() {
return peopleDao.findAll();
}
#Override
public People findById(int id) {
return peopleDao.findById(id);
}
/* ---------------------------------------------------- */
package com.example.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.example.test.entity.People;
import com.example.test.service.PeopleManager;
#Controller
public class PeopleController {
#Autowired
private PeopleManager peopleManager;
#RequestMapping(value = "/people/{id}", method = RequestMethod.GET)
public String home(Model model, #PathVariable("id") String id) {
People p;
try {
p = peopleManager.findById(Integer.parseInt(id));
if (p != null) {
model.addAttribute("message", "user exist, do any action");
} else {
model.addAttribute("message", "user NOT exist");
}
} catch (NullPointerException e) {
model.addAttribute("message", "user NOT exist");
}
return "people";
}
}
/* ---------------------------------------------------- */
Refactor the null check out of your controller. Controllers shouldn't have any business logic in them. The correct place for this is inside your service class.
#Override
#Transactional
public People findById(int id) throws ObjectNotFoundException{
People people = null;
people = peopleDao.findById(id);
if(people == null){
throw new ObjectNotFoundException("Couldn't find a People object with id " + id);
}
return people;
}
I would write a custom exception that extends RuntimeException that is thrown if your People object is null.
This is best practice as you can reuse your ObjectNotFoundException in all your service layers. Then make all your controller methods throw Exception and investigate global error handling for controllers.
Also, it is best practice to not annotate your entire service class as #Transactional, mark the individual methods. That way if you need to add additional methods to your services you can choose if you want them to run in a transactional context.
I'm busing developing an application (Hibernate Spring Vaadin Postgres Liferay).
I did all of the configurations for the project (Hibernate, Spring, Postgres) and
I generated a database, but when I do a dynamic formulaire I have a problem integrating the controller with the form.
This is the article.java:
package com.bd.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Articlet")
public class Article {
int id;
String nom;
String type;
int qte;
public Article() {
super();
// TODO Auto-generated constructor stub
}
#Id
#GeneratedValue
#Column(name="ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="Nom")
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
#Column(name="Type")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Column(name="Qunatite")
public int getQte() {
return qte;
}
public void setQte(int qte) {
this.qte = qte;
}
}
This is articledaoimpl.java:
package com.bd.dao;
import java.util.Collection;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.bd.entity.Article;
#Repository
#Configuration
#Transactional
public class ArticleDaoImp implements ArticleDao {
#Autowired
SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
#Transactional(readOnly = true)
public List<Article> getAll() {
return sessionFactory.getCurrentSession().createQuery("from Article")
.list();
}
#Transactional(readOnly = true)
public Article getById(int articleId) {
return (Article) sessionFactory.getCurrentSession().get(Article.class,
articleId);
}
#Override
public void save(Article article) {
sessionFactory.getCurrentSession().merge(article);
}
#Override
public void delete(Article article) {
sessionFactory.getCurrentSession().delete(article);
}
}
This is articleserviceimpl.java:
package com.bd.service;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import com.bd.dao.ArticleDao;
import com.bd.entity.Article;
#Service
#Configuration
#ComponentScan("com.bd.dao")
public class ArticleServiceImp implements ArticleService {
#Autowired
private ArticleDao articledao;
#Override
public Article getArticleById(int articleId) {
// TODO Auto-generated method stub
return articledao.getById(articleId);
}
#Override
public void saveArticle(Article article) {
// TODO Auto-generated method stub
articledao.save(article);
}
#Override
public void deleteArticle(Article article) {
// TODO Auto-generated method stub
articledao.delete(article);
}
#Override
public List<Article> getAllArticles() {
// TODO Auto-generated method stub
return articledao.getAll();
}
}
This is the article controleur:
package com.bd.controleur;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import com.bd.entity.Article;
import com.bd.service.ArticleService;
#Controller
#Configuration
#ComponentScan("com.bd.service")
public class ArticleControleur {
#Autowired
ArticleService articleService;
public void addarticle(Article article){
articleService.saveArticle(article);
}
}
This the form:
package achrefliferay;
import org.springframework.beans.factory.annotation.Autowired;
import com.bd.entity.Article;
import com.bd.service.ArticleService;
import com.vaadin.Application;
import com.vaadin.ui.Button;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Button.ClickEvent;
public class AchrefliferayApplication extends Application {
#Autowired
ArticleService articleService;
public void init() {
Article article;
Window w = new Window("Subscribe Newsletter");
setMainWindow(w);
w.setContent(new VerticalLayout());
TextField name = new TextField("Name");
TextField type = new TextField("Type");
TextField qte = new TextField("Quantité");
Button subscribeBtn = new Button("saisi");
w.addComponent(name);
w.addComponent(type);
w.addComponent(qte);
w.addComponent(subscribeBtn);
subscribeBtn.addListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
articleService.saveArticle();
}
});
}
}
You'll have to create a BeanItem and set it as the data source for your form. I don't know Spring that well, but once you know how to bind a bean to the form, you should be able to integrate the controller with the form by using the appropriate listeners.
Example:
// Create a form and use FormLayout as its layout.
final Form form = new Form();
// Set form caption text
form.setCaption("Subscribe Newsletter");
// Create a bean item that is bound to the bean.
final BeanItem item = new BeanItem(new Article());
// Bind the bean item as the data source for the form.
form.setItemDataSource(item);
// Add the subscribe button
HorizontalLayout formFooter = new HorizontalLayout();
Button subscribeButton = new Button("saisi");
subscribeButton.addListener(new Button.ClickListener() {
void buttonClick(Button.ClickEvent event) {
form.commit();
controller.addArticle(item.getBean());
}
});
formFooter.addComponent(subscribeButton);
form.setFooter(formFooter);
This means you don't have to explicitly create every form field like you did in your AchrefliferayApplication's init() method.
See Binding Form to Data in Book of Vaadin.
ps. If anyone actual Vaadin expert reads this: feel free to correct my answer to follow the best practices :)