Search code examples
javaspringmavenautowiredvaadin7

Spring Boot Vaadin7 Integration - Cannot bind with @Autowired


I created project with: http://start.spring.io/ I build it with maven and it's running.

So I'm creating entity Person:

@Entity
public class Person implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@Temporal(TemporalType.TIMESTAMP)
private Date birthDay;

@NotNull(message = "Name is required")
@Size(min = 3, max = 50, message = "Name must be longer than 3 and less than 40 characters")
private String name;

private Boolean colleague;

private String phoneNumber;

@NotNull(message = "Email is required")
@Pattern(regexp = ".+@.+\\.[a-z]+", message = "Must be valid email")
private String email;

 //----- GETTERS AND SETTERS -----------
}

For this entity Im creating repository PersonRepo:

public interface PersonRepo extends JpaRepository<Person, Long> {

@Override
<S extends Person> S save(S arg0);

@Override
long count();
}

Here is myUI class:

@SpringUI
@Theme("valo")
public class MyUI extends UI {
private static final long serialVersionUID = 1L;

private final PersonRepo personRepo;

@Autowired
private MyUI(PersonRepo personRepo) {
    this.personRepo = personRepo;
}

@Override
protected void init(VaadinRequest request) {
    VerticalLayout layout = new VerticalLayout();
    layout.setDefaultComponentAlignment(Alignment.MIDDLE_CENTER);

    Person person = new Person();
    person.setName("Person");
    person.setEmail("Email");
    person.setColleague(false);
    person.setBirthDay(new Date());
    personRepo.save(person);

    Label helloWorld = new Label();
    helloWorld.setValue("Persons: " + personRepo.count());
    helloWorld.setStyleName(ValoTheme.LABEL_H1);
    helloWorld.setSizeUndefined();

    layout.addComponent(helloWorld);

    setContent(layout);
}
}

Here I only @Autowire the PersonRepo, creating new Person and saving in db, than in Label I'm showing the count of Persons. But personRepo is null, the @Autowire is not working. I don't know where is my mistake...


Solution

  • Well @SpringBootApplication scan only components that are on the same package and below. Thats why Application cannot make @Autowire. In my example, every class is on different package.

    This we can fix if we put Application class into top package, or we can define @ComponentScan manually, to scan the specific package.