How does SimpleCORSFilter work? - spring

How does SimpleCORSFilter work in this example?
Enabling Cross Origin Requests for a RESTful Web Service.
I only see a declaration of SimpleCORSFilter class but no instance. I tried ctrl+f to search the example page but can't find anywhere this class be instantiated.
How does it work?
I am new to Spring and Java.
So more detail more helpful. Thx.

A main point of Spring is a mechanism called dependency injection. Spring allows you to mark your classes, instance variables and so on with special annotations. Spring will look for those annotations and configure your application according to them.
In your example you annotate your filter with #Component:
#Component
public class SimpleCORSFilter implements Filter
And you annotate your Application class with #SpringBootApplication:
#SpringBootApplication
public class Application
The second annotation (#SpringBootApplication) tells Spring to search through your project for #Component annotations. As you annotated your filter with this, Spring will find your filter and instantiate it automatically. That's how your filter will be created and put to the right place.

Related

How to make a bean discoverable by Quarkus CDI without using annotations

I have a simple Quarkus resource:
#Path("/rosters")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public class RosterResource {
private final RosterService rosterService;
public RosterResource(RosterService rosterService){
this.rosterService = rosterService;
}
#GET
#Path("/{rosterId}")
public Response getRoster(#PathParam("rosterId")Long rosterId){
return Response.ok(rosterService.getRosterById(rosterId)).build();
}
}
I am trying to inject the RosterServiceinstance in my resource, but I am getting a javax.enterprise.inject.UnsatisfiedResolutionException. However, if I use the #ApplicationScoped annotation on RosterService, then everything works just fine. Is there a way of injecting the RosterService class in my resource without using annotations? In other words, is there a way of making RosterService discoverable by the Quarkus container without directly annotating the class?
Edit: looking into the CDI docs, it seems that you can manually register beans using a method with a #BuildStep annotation. However, it is not clear to me which class should contain the annotated method)
Another option would be to use a Jandex index
To the best of my knowledge, Quarkus only implements so called annotated bean discovery. That means that all CDI beans in Quarkus have to have a bean defining annotation. #ApplicationScoped is one of them.
EDIT: regarding a Jandex index, that allows you to scan for beans in additional JARs. In other words, it will only expand the set of classes that are scanned for a bean defining annotation.
When it comes to a #BuildStep method -- that is only possible in a Quarkus extension. Extensions are powerful (and indeed they can define additional beans) but also complex. You can start at https://quarkus.io/guides/building-my-first-extension, but it may feel overwhelming. It may also feel like this is not the right thing to do if you want to just make your class a bean -- and that would be true. But if your class comes from an external library that you can't change, extension makes sense.
Is there a specific reason why you don't want to annotate your service class with #ApplicationScoped (or any other of the bean discover/scope annotations)?
The only other way that I'm aware of (instead of annotations) is - as you yourself mentioned - the use of Jandex index.

How SpringBoot dependency injection works with different type of annotations

I recently started exploring Spring Boot. I see that there are 2 ways to define Beans in Spring Boot.
Define #Bean in the class annotated with #SprinBootApplication
Define #Bean in a class annotated with #Configuration
I am also confused about stereo-type annotation #Repository #Service #Controller etc.
Can someone please explain how dependency-injection works with these annotations?
Yes it is possible.
Either you use #Bean in any of your #Configuration or #SpringBootApplication class or mark the bean classes explicitly with annotations like #Service, #Component #Repository etc.
#Service or #Component
When you mark a class with #Service or #Compoenent and if spring's annotation scanning scope allows it to reach to the package, spring will register the instances of those classes as spring beans.
You can provide the packages to be included/excluded during scan with #ComponentScan
#Bean
#Beans are marked on factory methods which can create an instance of a particular class.
#Bean
public Account getAccount(){
return new DailyAccount();
}
Now in you application you can simply #Autowire Account and spring will internally call its factory method getAccount, which in turn returns an instance of DailyAccount.
There is a simple difference of using #Bean vs #Service or #Compoenent.
The first one makes your beans loosely coupled to each other.
In the #Bean, you have flexibility to change the account implementation without even changing any of the account classes.
Consider if your classes instantiation is a multi-step operation like read properties values etc then you can easily do it in your #Bean method.
#Bean also helps if you don't have source code access to the class you are trying to instantiate.
Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added.
You need to opt-in to auto-configuration by adding the #EnableAutoConfiguration or #SpringBootApplication annotations to one of your #Configuration classes.
You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies. For simplicity, we often find that using #ComponentScan (to find your beans) and using #Autowired (to do constructor injection) works well.
One way is to define #Bean in the class annotated with
#SprinBootApplication
If you see #SprinBootApplication it is combination of many annotation, and one of them is #Configuration. So when you define #Bean in the Main class, it means it's inside #Configuration class.
According to Configuration docs :
Indicates that a class declares one or more #Bean methods and may be
processed by the Spring container to generate bean definitions and
service requests for those beans at runtime.
class annotated with #Configuration
When you define #Bean is a class annotated with #Configuration class, it means it is the part of spring configuration all the Beans define in it all available for Dependency-Injection.
I have also seen some code where neither of the 2 above approaches
have been used and yet dependency injection works fine. I have tried
to research a lot on this but could not find any concrete answer to
this. Is this possible?
I am assuming you are talking about Sterio-type annotation. Every sterio type annotation has #Component, according to docs :
Indicates that an annotated class is a "component". Such classes are
considered as candidates for auto-detection when using
annotation-based configuration and classpath scanning.

spring-aop "None or multiple beans found in Spring context for type class"

I am not able to apply an aspect to my spring rest endpoint components for logging purposes.
All of endpoint classes are implemented like
#Component
#Path("mypath")
public class MyEndpointImpl extends MyEndpoint
{...}
Without aspect everything works fine without any errors. When I try to apply aspect I just get list of errors for each endpoint class like "None or multiple beans found in Spring context for type class **.*EndpointImpl" and no aspect is intercepting endpoints' methods. However everything works fine as if there were no error message and no aspect.
Interesting is when I create e.g. simple filter
#Component
#WebFilter(filterName = "MySimpleFilter", urlPatterns = "/*")
public class SimpleFilter implements javax.servlet.Filter
{...}
in package of pointcut, doFilter method of SimpleFilter is intercepted by the aspect as would expect for all endpoint methods.
What could be a problem here, any ideas?
In my environment the Problem disappeared when adding the following to the application.yml file
spring.aop.proxy-target-class: true

Analog of spring #Controller annotation in Java config

In Spring DI I love to use #Bean with factory method in #Configuration class instead of using #Component annotation explicitly. Is there a way to do the same with #Controller annotation for Spring Web? In another words, could I declare controller via factory method in some #Configuration class instead of explicit annotation?
Thats not possible since #Controller can only be placed on types. But more important are the methods. I assume you have multiple methods with #RequestMethod annotations. You can place as much methods as you like in this controller with differnet paths. Which should end up in around the same thing as you want?

HystrixCommand only works with Spring Service or Component?

Does Spring Hystrix only work with #Service and #Component?
I had a class that was defined as a #RestController and my HystrixCommand would not fire, the method would execute but not behave as a HystrixCommand. When I made a #Service class and put the HystrixCommand method and fallback into it the HystrixCommand would work properly.
What are the appropriate Spring annotations that can be used with #EnableHystrix?
For now, you described the appropriate places. We have an open issue that mentions support for controllers.

Resources