Grpc Spring Boot Starter - spring-boot

I am trying to integrate a grpcService to my spring boot application. In this service class i have a jpaRepository which is #Autowired. When i run the server this repository is not injected( is null when i'm trying to use it).
#Service
public class MedicationPlanService extends medicationPlanGrpc.medicationPlanImplBase {
#Autowired
private MedicationPlanRepository medicationPlanRepository;
#Override
public void hello(MedicationPlan.HelloRequest request, StreamObserver<MedicationPlan.HelloResponse> responseObserver) {
List<MedicationPlan> medicationPlans = medicationPlanRepository.findAll();
MedicationPlan.HelloResponse.Builder response = MedicationPlan.HelloResponse.newBuilder();
response.setResponseMessage("hello");
responseObserver.onNext(response.build());
responseObserver.onCompleted();
}
}
#Component
public class GrpcServerStartConfiguration {
#PostConstruct
public void startGrpcServer() throws IOException, InterruptedException {
Server server = ServerBuilder.forPort(9091).addService(new MedicationPlanService()).build();
server.start();
System.out.println("gRPC server started");
server.awaitTermination();
}
}
When i try to use the medicationPlanRepository i realized that it is null.
Thanks in advance :).

Because you're creating MedicationPlanService with "new", it becomes a simple object, not a bean. And things such as DI don't work in this way.
Initialize these 2 classes correctly (via #ComponentScan or #Bean in #Configuration class). Then inject MedicationPlanService into GrpcServerStartConfiguration. The latter you can mark as #Configuration for better understaning btw.

Related

Spring #Bean - creation of Spring Bean depends on service class name

I use Spring 4.2.8 and I do have the service class below. If this class has the name ScheduleEmailCreateAndSendServiceImpl than everything works fine (method generalEmailMessage is invoked at start time in order to create the Spring Bean)
If I rename this class to EmailCreateAndSendServiceImpl than method generalEmailMessage will not be invoked at start time - does anyone know why?
#Service("emailCreateAndSendService")
public class ScheduleEmailCreateAndSendServiceImpl extends AbstractService
implements EmailService {
protected EmailMessage generalMessage;
#Override
public void createAndSendMessage(String receiver, boolean emailActive, Object[] values) throws BusinessException {
// create and send email
}
#Bean
public EmailMessage generalEmailMessage() {
this.generalMessage = new GeneralEmailInformationMessage();
return generalMessage;
}
}
[EDIT]
with this code it is the same
#Configuration
public #Data class ScheduleGeneralEmailConfiguration {
protected EmailMessage generalMessage;
public ScheduleGeneralEmailConfiguration() {
System.out.println("asdf");
}
#Bean
public EmailMessage generalEmailMessage() {
this.generalMessage = new GeneralEmailInformationMessage();
return generalMessage;
}
}
#Bean annotated methods should be in #Configuration annotated class.
You can also put the #Bean annotated methods in the main class of the Spring Boot application annotated with #SpringBootApplication which encapsulates #Configuration, #EnableAutoConfiguration, and #ComponentScan annotations.
Make sure your #Configuration annotated class is placed in the same package or sub package of the Spring Boot Application class

Springboot>WebServlet - Pass spring container

I have springBoot standalone application. I used #SpringBootApplication, #ServletComponentScan annotations in my standalone application. All my components, beans getting initialized in spring container and prints in the application startup.
Inside my servlet, i invoke handler and beans were coming as null. How do i pass spring container through my servlet ?
#SpringBootApplication
#ServletComponentScan
public class AStandaloneApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(AStandaloneApplication.class, args);
}
}
#WebServlet("/ba")
public class BAServlet extends SpeechletServlet {
#Autowired
private BASpeechletHandler bASpeechletHandler;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
this.setSpeechlet(bASpeechletHandler);
}
}
public class BASpeechletHandler implements Speechlet {
#Autowired
private BSEngine bSEngine;
#Autowired
private IBotResponseObjToAlexaSpeechletResponseObj botResponseObjToAlexaSpeechletResponseObj;
}
The bASpeechletHandler is null in servlet, if i instatiate object in my servlet for bASpeechletHandler and move on then components, services and repository inside bASpeechletHandler also null.
Thanks.
1.Add the packages to component scan - similar to this
#ServletComponentScan(basePackages="org.my.pkg")
2.Add one of the #Component annotations into your BASpeechletHandler class.
This will make that class eligible for auto-discovery of beans.
May be i little complication in asking. I found the solution. In Web applicationContext i pinged the spring context and got the bean.
private ApplicationContext appContext;
private BASpeechletHandler bASpeechletHandler;
public void init(ServletConfig config) throws ServletException {
super.init();
appContext = (ApplicationContext) config.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
bASpeechletHandler = (bASpeechletHandler) appContext.getBean("bASpeechletHandler");
}
Thanks.

How to use CDI into JAX-RS client

I have searched a while on SO and official documentation but I cannot found a way to use directly CDI injection into a JAX-RS client.
I retrieve a client using the builder method and I want to register a WriterInterceptor (or any filter like component) which uses injection to retrieve another bean.
I want to use CDI injection and avoid registering each bean with HK2.
ClientBuilder.newBuilder()
.register(MyWriter.class)
.build();
And MyWriter with the injected class.
#Provider
public class MyWriter implements WriterInterceptor {
private final MyRepo repo;
#Inject
public MyWriter(MyRepo repo) {
this.repo = repo;
}
#Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
context.proceed();
}
}
public class MyRepo {
}
I am running in an embedded jetty with Jersey 2 and Weld SE.
Its possible to inject in java se application using wield .
#Singleton
public class Application {
private static Logger logger = LoggerFactory.getLogger(Application.class);
#inject
private SomeOtherBean injectedBean;
public void run() {
logger.debug("application initialized");
injectedBean.doSomething();
}
}
inside main initialize weild
import java.io.IOException;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
public class EntryPoint {
public static void main(String[] args) throws IOException {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
Application application = container.instance().select(Application.class).get();
application.run();
weld.shutdown();
}
}
Have a look at below doc
https://docs.jboss.org/weld/reference/latest/en-US/html/environments.html#_java_se
also below tutorial
https://randling.wordpress.com/2011/08/15/cdi-in-java-se/
If I understand everything correctly, this has already been asked and answered. In a nutshell: you have to override the default behaviour of the H2K Binder, so it reaches for the Weld Bean Manager. You don't have to register every Bean with H2K later on.
Edit: to contain everything in the post, so you don't have to read the comments:
The linked answer is for the server-side, not the client.
With standard tools (Jersey Client-side injection providers and the Weld bridge), it seems to be a too big overhead/impossible to do
Apparently in the Dropwizard project they managed to do custom client-side injection.

getting #autowired intance null when try trying to do operation on it,throwing null pointer exception

I am trying to save data on gemfire using crud repository. I have created one operation class to call save method of repository but at autowired instance I am getting null pointer exception. Below is my code:
public interface GeodeRepository extends CrudRepository<KeyValueBean, String> {
#Override
public KeyValueBean findOne(String name);
#Override
public <S extends KeyValueBean> Iterable<S> save(Iterable<S> entities);
}
#EnableGemfireRepositories(basePackageClasses = GeodeRepository.class)
#EnableAutoConfiguration
#Configuration
public class Operations {
#Autowired
private GeodeRepository repository;
public void saveKeyValueData(KeyValueBean keyValueBean) {
System.out.println("Repository is : " + repository);
repository.save(Arrays.asList(keyValueBean)); // <--- i am getting
// repository as null so
// getting null pointer
// exception
}
}
When we #Autowired any class make sure, you have declared that class as a #Component.
for example:
#Component
public class Operations {
#Autowired
private GeodeRepository repository;
public void saveKeyValueData(KeyValueBean keyValueBean) {
System.out.println("Repository is : " + repository);
repository.save(Arrays.asList(keyValueBean));
}
}
and try using #Autowired to Operation class to your class
in which class your are calling your saveKeyValueData() method.
So, what is not apparent from your example is how you "bootstrap" your application and it's features (e.g. Repositories) into action.
It is not simply enough to add the Spring #Configuration, Spring Boot's #EnableAutoConfiguration and SD GemFire's #EnableGemfireRepositories annotations and expect everything to be auto-configured and wired up successfully. I.e. you need a bootstrapping mechanism, like Spring Boot, especially if you are using the #EnableAutoConfiguration annotation.
For example...
import org.springframework.boot.SpringApplication;
...
class MyApplication {
public static void main(String[] args) {
SpringApplication.run(Operations.class, args);
}
}
Now, you could remove the #EnableAutoConfiguration from your Operations class and add the #SpringBootApplication to the MyApplication class, like so...
#SpringBootApplication
class MyApplication {
...
}
#SpringBootAppliation combines together Spring's #Configuration with Spring Boot's #EnableAutoConfiguration, along with many other useful meta-annotations, like Spring's #ComponentScan, enabling all sorts of magic to happen.
But, if you are not using Spring Boot, you can always bootstrap you application with the AnnotationConfigApplicationContext, like so..
class MyApplication
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(Operations.class);
applicationContext.registerShutdownHook();
}
}
This is essentially what the Spring Boot, SpringApplication class does for you anyway.
If you are developing a Web application, then of course you can specify the type of ApplicationContext created since you are using Java config, for instance. See here for more details.
Hope this helps!
Cheers,
John

Why Spring's #Component does not work on a JSP Custom Tag class?

I have a custom tag:
#Component
public class CVTag extends SimpleTagSupport {
#Inject
private JaxbSupport jaxbSupport;
#Override
public void doTag() throws JspException, IOException {
JspWriter writer = getJspContext().getOut();
Groups groups = jaxbSupport.getJaxbGroups();
}
NullPointerException is thrown as jaxbSupport is null.
Is there really a limitation stipulating Custom-Tag cannot be a Spring managed Bean? or I am doing something wrong?
Using Spring 3.2.4.
Thanks.

Resources