Aspect in Spring boot Custom Annotation - java

I am creating a custom annotation NullCheck for method parameter to check value is null or not hello(#NullCheck String text), but I am not able to invoke Aspect around the Annotation.
Main Class
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
#SpringBootApplication
#EnableAutoConfiguration
#EnableAspectJAutoProxy
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Controller class, just invoking an aspect for POC, not returning anything
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/")
class HelloController {
#GetMapping
public void hello() {
hello("hi");
}
private void hello(#NullCheck String text) {
System.out.println(text);
}
}
Annotation
package com.example.demo;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
#Documented
#Retention(RUNTIME)
#Target(ElementType.PARAMETER)
public #interface NullCheck { }
Aspect
package com.example.demo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
#Aspect
#Component
public class NullCheckAspect {
this is working
#Before("#annotation(org.springframework.web.bind.annotation.GetMapping)")
but this is not
#Before("#annotation(com.example.demo.NullCheck)")
public void beforeAdvice(JoinPoint joinPoint) {
System.out.println("Before method:" + joinPoint.getSignature());
}
}
build.gradle
buildscript {
ext {
springBootVersion = '2.1.2.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
idea {
module {
// if you hate browsing Javadoc
downloadJavadoc = true
// and love reading sources :)
downloadSources = true
}
}
bootJar {
launchScript()
}
repositories {
mavenCentral()
jcenter()
}
bootJar {
launchScript()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-aop'
implementation 'org.springframework.boot:spring-boot-starter-web'
runtimeOnly 'org.springframework.boot:spring-boot-devtools'
}
what am I missing?

As per my understanding and after doing some search on google, you can get method parameter and its value with particular annotation with following code:
package com.example.demo;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
#Component
#Aspect
public class NullCheckAspect {
#Around("execution(* com.example.demo.HelloController.nullChecker(String))")
public Object around(ProceedingJoinPoint pJoinPoint) throws Throwable {
Object[] args = pJoinPoint.getArgs();
Method method = MethodSignature.class.cast(pJoinPoint.getSignature()).getMethod();
Annotation[][] parametersAnnotations = method.getParameterAnnotations();
Map<String, Object> annotatedParameters = new HashMap<>();
int i = 0;
for(Annotation[] parameters : parametersAnnotations) {
Object arg = args[i];
String name = method.getParameters()[i++].getDeclaringExecutable().getName();
for(Annotation parameter: parameters) {
if ((parameter instanceof NullCheck)) {
System.out.println("Found the null checker annotation with name: " + name);
System.out.println("Found the null checker annotation with arg: " + arg);
annotatedParameters.put(name, arg);
}
}
}
System.out.println(annotatedParameters);
return pJoinPoint.proceed(args);
}
}
And with the interface annotation:
package com.example.demo;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.springframework.stereotype.Component;
#Component
#Retention(RUNTIME)
#Target(ElementType.PARAMETER)
public #interface NullCheck {
}
More details about my code you can check it at my github repository, I have created spring boot demo version and pushed it for you at https://github.com/krishnaiitd/learningJava/blob/master/springBoot/gs-spring-boot/src/main/java/com/example/demo/HelloController.java
This also include other type of aspects like tracking the time of a particular methods.
Hope this will help you to get the basic understanding of #Aspect in Spring boot.

I don't know why it is as it is but I had the same issue. This is can be solved easily by using Pointcuts, for example:
#Before("nulllCheckAnnotation()")
public void beforeAdvice(JoinPoint joinPoint) {
System.out.println("Before method:" + joinPoint.getSignature());
}
}
#Pointcut("#annotation(com.example.demo.NullCheck)")
private void nulllCheckAnnotation() { }
Read more about pointcuts here if you interested: https://www.baeldung.com/spring-aop-pointcut-tutorial

Related

#RunWith(MockitoJUnitRunner.class) mocks are null

I am using the "RunWith(MockitoJUnitRunner.class)", the #Mock notationt to mock the service and the #InjectMocks notation to inject the mock service to the controller. I get a NullPointerException in the ChargingStationsControllerTest:40, in the "when". I debugged and realized that the mocks are null.
Here is my code:
package com.example.assignmentchargingstations.controllers;
import com.example.assignment.chargingStations.controllers.ChargingStationsController;
import com.example.assignment.chargingStations.models.AddressInfo;
import com.example.assignment.chargingStations.models.ChargingStation;
import com.example.assignment.chargingStations.models.StatusType;
import com.example.assignment.chargingStations.services.OpenChargeMapService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.ArgumentMatchers.anyDouble;
import static org.mockito.Mockito.when;
#RunWith(MockitoJUnitRunner.class)
public class ChargingStationsControllerTest {
#Mock
private OpenChargeMapService openChargeMapService;
#InjectMocks
private ChargingStationsController chargingStationsController;
#Test
public void testGetNearestChargingStations() throws Exception {
Double latitude = 90.0;
Double longitude = 90.0;
List<ChargingStation> chargingStationsListExpected = new ArrayList<>();
StatusType statusTypeExpected = StatusType.builder().IsOperational(true).build();
AddressInfo addressInfoExpected = AddressInfo.builder().Latitude(latitude).Longitude(longitude).Title("Test Charging Station").build();
chargingStationsListExpected.add(ChargingStation.builder().StatusType(statusTypeExpected).AddressInfo(addressInfoExpected).build());
when(openChargeMapService.getNearestChargingStations(anyDouble(), anyDouble())).thenReturn(chargingStationsListExpected);
ResponseEntity<List<ChargingStation>> responseExpected = chargingStationsController.getNearestChargingStations(latitude, longitude);
Assertions.assertEquals(responseExpected.getStatusCode(), HttpStatus.OK);
Assertions.assertEquals(responseExpected.getBody(), chargingStationsListExpected);
}
}
The controller that I'm testing:
package com.example.assignment.chargingStations.controllers;
import com.example.assignment.chargingStations.models.ChargingStation;
import com.example.assignment.chargingStations.services.OpenChargeMapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
#Controller
public class ChargingStationsController {
private final OpenChargeMapService openChargeMapService;
public ChargingStationsController(OpenChargeMapService openChargeMapService) {
this.openChargeMapService = openChargeMapService;
}
#RequestMapping(path = "/nearest-charging-stations", method = RequestMethod.GET)
public ResponseEntity<List<ChargingStation>> getNearestChargingStations(#RequestParam Double latitude, #RequestParam Double longitude) {
List<ChargingStation> nearestChargingStations = openChargeMapService.getNearestChargingStations(latitude, longitude);
return new ResponseEntity<>(nearestChargingStations, HttpStatus.OK);
}
}
The service:
package com.example.assignment.chargingStations.services;
import com.example.assignment.chargingStations.clients.OpenChargeMapClient;
import com.example.assignment.chargingStations.models.ChargingStation;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
#Service
public class OpenChargeMapService {
private static final Double MAX_LATITUDE = 90.0000000;
private static final Double MIN_LATITUDE = -90.0000000;
private static final Double MAX_LONGITUDE = 180.0000000;
private static final Double MIN_LONGITUDE = -180.0000000;
private final OpenChargeMapClient openChargeMapClient;
public OpenChargeMapService(OpenChargeMapClient openChargeMapClient) {
this.openChargeMapClient = openChargeMapClient;
}
public List<ChargingStation> getNearestChargingStations(Double latitude, Double longitude) {
validateLatitudeLongitude(latitude, longitude);
List<ChargingStation> chargingStationsList = openChargeMapClient.getNearestChargingStations(latitude, longitude);
return chargingStationsList;
}
private void validateLatitudeLongitude(Double latitude, Double longitude) {
if (isLatitudeOutOfRange(latitude) || isLongitudeOutOfRange(longitude)) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Values for latitude and longitude are out of range.");
}
}
private boolean isLatitudeOutOfRange(Double latitude) {
return (latitude.compareTo(MIN_LATITUDE) < 0) || (latitude.compareTo(MAX_LATITUDE) > 0);
}
private boolean isLongitudeOutOfRange(Double longitude) {
return (longitude.compareTo(MIN_LONGITUDE) < 0) || (longitude.compareTo(MAX_LONGITUDE) > 0);
}
}
The build.gradle:
plugins {
id 'org.springframework.boot' version '2.5.1'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.projectlombok:lombok:1.18.18'
implementation 'junit:junit:4.13.1'
annotationProcessor 'org.projectlombok:lombok:1.18.18'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
Since you are using Spring Boot. You have two options. You can either test the class in isolation or you can load in the spring context.
Both approaches have their benefits and limitations.
Supply mock directly into the class in test.
public class Test {
ClassToMock service = mock(ClassToMock.class)
ClassInTest testService = new ClassInTest(service);
#Test
public void doTest() {
....
}
}
This approach, you are supplying a mock directly into your service in test. This will result in speedier runtimes, but you will not be able to do more comprehensive integration tests.
Load mock service directly into spring context
#SpringBootTest
#RunWith(SpringJUnit4ClassRunner.class)
public class Test {
#MockBean
ClassToMock service;
#Autowired
ClassInTest testService;
#Test
public void doTest() {
....
}
}
This will generate the spring context and mock the service component you have created. Doing so would test the wiring of your beans and your service in test. You will also have more flexibility in case you want to mock an encapsulating service (i.e. repository layer/data layer). You should also be able to use #Mock & #InjectMock with the class annotation you are currently using.

NoSuchBeanDefinitionException: No bean named 'authService' available

When trying to use the api, I get this error:
"org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'authService' available".
How do I make the authservice be found by the app? I've gotten a similar error before, which I tried to fix by adding all the packages you see below in the Main class.
The Main class:
package com.lvwangbeta.poplar.api;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.lvwangbeta.poplar.action.PoplarActionServiceApplication;
import com.lvwangbeta.poplar.feed.PoplarFeedServiceApplication;
import com.lvwangbeta.poplar.tag.PoplarTagServiceApplication;
import com.lvwangbeta.poplar.user.PoplarUserServiceApplication;
import java.util.List;
#SpringBootApplication(scanBasePackages= {"com.lvwangbeta.poplar.common","com.lvwangbeta.poplar.common.intr","com.lvwangbeta.poplar.action",
"com.lvwangbeta.poplar.api.service",
"com.lvwangbeta.poplar.feed","com.lvwangbeta.poplar.tag",
"com.lvwangbeta.poplar.user", "com.lvwangbeta.poplar.api"})
//#ComponentScan({"com.lvwangbeta.poplar.common","com.lvwangbeta.poplar.user","com.lvwangbeta.poplar.feed.dao", "com.lvwangbeta.poplar.api"})
#ComponentScan({"com.lvwangbeta.poplar.action.dao.impl","com.lvwangbeta.poplar.feed.dao.impl"})
#MapperScan({"com.lvwangbeta.poplar.action.dao","com.lvwangbeta.poplar.feed.dao","com.lvwangbeta.poplar.tag.dao"})
public class PoplarApiApplication extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
//Object[] sources = {PoplarApiApplication.class,PoplarTagServiceApplication.class};
//SpringApplication.run(sources, args);
System.out.println("Started");
SpringApplication.run(PoplarApiApplication.class, args);
//SpringApplication.run(PoplarTagServiceApplication.class, args);//I hope this works
//SpringApplication.run(PoplarActionServiceApplication.class, args);
//SpringApplication.run(PoplarFeedServiceApplication.class, args);
//SpringApplication.run(PoplarUserServiceApplication.class, args);
}
#Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
super.addArgumentResolvers(argumentResolvers);
argumentResolvers.add(new RequestAttributeArgumentResolver());
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
registry.addInterceptor(new APIAccessAuthRequiredInterceptor())
.addPathPatterns("/api/v1/**")
.excludePathPatterns("/api/v1/user/login/**")
.excludePathPatterns("/api/v1/user/check/email/*")
.excludePathPatterns("/api/v1/user/register/**")
.excludePathPatterns("/api/v1/feed/of/user/**");
}
}
The AuthService class:
package com.lvwangbeta.poplar.api.service;
import com.lvwangbeta.poplar.common.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
#Service("authService")
public class AuthService {
#Autowired
private RedisTemplate<String, String> redisTemplate;
#Resource(name="redisTemplate")
private HashOperations<String, String, Object> mapOps;
public User getUserByToken(String token) {
return (User) mapOps.get("tokens:", token);
}
}
What am I missing? It's not registering even though the api link is there. I'm trying to combine many microservices to one, and so there's alot of packages.
include com.lvwangbeta.poplar.api.service in #ComponentScan
Like this :
#ComponentScan({"com.lvwangbeta.poplar.action.dao.impl","com.lvwangbeta.poplar.feed.dao.impl", "com.lvwangbeta.poplar.api.service"})
Suggestion :For simple applications avoid configuring the way above.
Keep your project structure as explained in this reference and #SpringBootApplication is enough.
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-locating-the-main-class

Spring AOP works without #EnableAspectJAutoProxy?

I am learning Spring (currently its AOP framework). Even though all sources I've read say that to enable AOP one needs to use #EnableAspectJAutoProxy annotation (or its XML counterpart) my code seems to work with annotation commented out. Is that because I use Lombok or Spring Boot (v. 1.5.9.RELEASE, dependent on Spring v. 4.3.13.RELEASE)?
Minimal example follows:
build.gradle
buildscript {
ext {
springBootVersion = '1.5.9.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
group = 'lukeg'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter')
compileOnly('org.projectlombok:lombok')
compile("org.aspectj:aspectjweaver:1.8.11")
testCompile('org.springframework.boot:spring-boot-starter-test')
}
ApplicationConfiguration.java (note the AOP annotation is commented out)
package lukeg;
import org.springframework.context.annotation.*;
#Configuration
#ComponentScan
//#EnableAspectJAutoProxy
public class ApplicationConfiguration {
#Bean
TestComponent testComponent() {
return new TestComponent();
}
}
LearnApplication.java
package lukeg;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
#SpringBootApplication
public class LearnApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(LearnApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
TestComponent testComponent = context.getBean(TestComponent.class);
System.out.println(""+testComponent);
}
}
LoggerHogger.java
package lukeg;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
#Component
#Aspect
public class LoggerHogger {
#Pointcut("execution(* lukeg*.*.toString(..))")
public void logToString() {}
#Before("logToString()")
public void beforeToString () {
System.out.println("Before toString");
}
}
TestComponent.java
package lukeg;
import lombok.Data;
#Data
public class TestComponent {
}
The #SpringBootApplication annotation contains the #EnableAutoConfiguration annotation. This autoconfiguration is one of the attractions of Spring Boot and makes configuration simpler. The auto configuration uses #Conditional type annotations (like #ConditionalOnClass and #ConditionalOnProperty) to scan the classpath and look for key classes that trigger the loading of 'modules' like AOP.
Here is an example AopAutoConfiguration.java
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.Advice;
import org.aspectj.weaver.AnnotatedElement;
#Configuration
#ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class,
AnnotatedElement.class })
#ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
public class AopAutoConfiguration {
#Configuration
#EnableAspectJAutoProxy(proxyTargetClass = false)
#ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false", matchIfMissing = false)
public static class JdkDynamicAutoProxyConfiguration {
}
#Configuration
#EnableAspectJAutoProxy(proxyTargetClass = true)
#ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", matchIfMissing = true)
public static class CglibAutoProxyConfiguration {
}
}
As you can see, if you add one of the above aop classes to your class path (or property), Spring will detect it and effectively behave as if you had the #EnableAspectJAutoProxy annotation on your main class.
Your project has a file LoggerHogger which has an #Aspect.

Primitive type dependency injection in spring boot

Can you please provide me with an example of primitive type dependency injection in spring boot. I have tried once but TestConfiguration which is my custom bean definition class does not detect or does not recognize by spring boot application.
here is my code,
//Engine class
package com.test2.projectTest;
import org.springframework.stereotype.Component;
#Component
public class Engine {
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
//Test Configuration
package com.test2.projectTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class TestConfiguration {
#Bean("engine")
public Engine engine(){
Engine engine = new Engine();
engine.setMsg("Message is injected");
return engine;
}
}
//spring main application
package com.test2.projectTest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class ProjectTestApplication {
public static void main(String[] args) {
SpringApplication.run(ProjectTestApplication.class, args);
}
}
//JUnit Test
package com.test2.projectTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest
public class ProjectTestApplicationTests {
#Test
public void contextLoads() {
ApplicationContext apc = new
AnnotationConfigApplicationContext(TestConfiguration.class);
Engine e = (Engine) apc.getBean("engine");
e.getMsg();
}
}
// Output - org.springframework.beans.factory.NoSuchBeanDefinitionException:
No bean named 'engine' available
Please suggest any solution to above issue
Add #componentscan annotation in main class and provide engine class package and it should work

Vaadin + Spring Boot errors: "Cannot enhance #Configuration" and "More than one Servlet Mapping defined"

I'm new to Spring and Vaadin. I'm trying to go through tutorial for views navigation.
I'd like to enable #Push in future to update views periodically with data fetched from DB.
The project is very, very simple. I use no configuration class nor any XML - only Java annotations.
Could anyone help me to fix the example code? Because I'm getting following warnings and I'm not sure what can be done with it and what will be the result of ignoring them.
First one is:
onClassPostProcessor : Cannot enhance #Configuration bean definition 'com.vaadin.spring.VaadinConfiguration' since its singleton instance has been created too early.
The typical cause is a non-static #Bean method with a BeanDefinitionRegistryPostProcessor return type:
Consider declaring such methods as 'static'.
And another one is only when I add compile("com.vaadin:vaadin-push") dependancy:
o.a.util.IOUtils : More than one Servlet Mapping defined.
WebSocket may not work org.apache.catalina.core.ApplicationServletRegistration
AppMain
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class AppMain {
public static void main(String[] args) {
SpringApplication.run(AppMain.class, args);
}
}
MyUI
import com.vaadin.annotations.Theme;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewDisplay;
import com.vaadin.server.VaadinRequest;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.spring.annotation.SpringViewDisplay;
import com.vaadin.ui.*;
import com.vaadin.ui.themes.ValoTheme;
#Theme("valo")
#SpringUI(path = "/ui")
#SpringViewDisplay
public class MyUI extends UI implements ViewDisplay {
private Panel springViewDisplay;
#Override
protected void init(VaadinRequest request) {
final VerticalLayout root = new VerticalLayout();
root.setSizeFull();
setContent(root);
final CssLayout navigationBar = new CssLayout();
navigationBar.addStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
root.addComponent(navigationBar);
springViewDisplay = new Panel();
springViewDisplay.setSizeFull();
root.addComponent(springViewDisplay);
root.setExpandRatio(springViewDisplay, 1.0f);
}
#Override
public void showView(View view) {
springViewDisplay.setContent((Component) view);
}
}
DefaultView
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
import javax.annotation.PostConstruct;
#SpringView(name = DefaultView.VIEW_NAME)
public class DefaultView extends VerticalLayout implements View {
public static final String VIEW_NAME = "";
#PostConstruct
void init() {
addComponent(new Label("This is the default view"));
}
#Override
public void enter(ViewChangeListener.ViewChangeEvent event) {
// This view is constructed in the init() method()
}
}
build.gradle
buildscript {
ext { springBootVersion = '1.5.6.RELEASE' }
repositories { mavenCentral() }
dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") }
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories { mavenCentral() }
ext { vaadinVersion = '8.1.0' }
dependencies {
compile('com.vaadin:vaadin-spring-boot-starter')
compile("com.vaadin:vaadin-push")
compile("org.springframework.boot:spring-boot-starter-logging")
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
imports { mavenBom "com.vaadin:vaadin-bom:${vaadinVersion}" }
}
application.properties
server.port=8091

Categories