I was wondering what is the difference between creating a new class and injecting it with the #Autowired annotation and creating a class and take the object of this class and using its methods. Is there any techical reason(i.e. faster access etc)?
Service case:
#Service
public class AuthorService implements AuthorServiceInterface {
//some methods
}
Simple Class case:
public class AuthorService implements AuthorServiceInterface {
//some methods
}
If i want to call the first one in another class i have to write:
public Class myclass{
#Autowired
AuthorService authorservice;
}
In the second case i have to write:
public Class myclass{
AuthorService authorservice = new AuthorService():
}
Whats the difference between these two cases?
The first snippet uses dependency injection, and the second doesn't. Dependency injection allows
decoupling MyClass from the concrete implementation of AuthorService which would allow switching implementations depending on the environment for example
using a singleton (or session-scoped or request-scope) AuthorService rather than reinstantiating one each time
injecting a mock AuthorService implementation when unit-testing MayClass
injecting a proxy around the concrete AuthorService instance, which could
verify authorizations
start a transaction before each method call and commit/rollback it after the method call
log the method calls
measure the time taken by methods and compute statistics
invoke an AuthorService on another machine, using RMI or HttpInvoker
...
Note that you should autowire AuthorServiceInterface, and not AuthorService, in MyClass.
Related
I'm working on a spring project from our customer.
Below is the code for controller
#Log4j2
#RestController
#AllArgsConstructor
#RequestMapping(path = "/api/theapi")
#Api(value = "Description for the API")
public class TheAPIController {
private final ModelMapper modelMapper;
private final ObjectMapper objectMapper;
private final TheDemoService demoService;
...other code for controller
}
Below is the code for Service:
#Service
public class TheDemoService{ ... }
I was so surprise about 2 things:
Question 1: Why we need to use #AllArgsConstructor from project Lombok?
As per my understanding, Spring provide #RestController that Spring runtime container will initialize an Instance for our Controller. So that, having a constructor for our Controller seems like an invalid approach for using Spring Inversion of Control, is this correct?
Question 2. Because of using #AllArgsConstructor, somehow, the instance for demoService is to be injected
But again, I surprise because the code of Controller does not have #Autowired in combine with demoService.
In the actual code, there is no #Autowired for "private final TheDemoService demoService".
Hence, I could think of a possibility there, is that because of Lombok's #AllArgsConstructor would inject an instance of our TheDemoService via a constructor of
TheAPIController, I could not reason anything about this logic.
It's Invalid approach, no need for defining constructor for RestController
It's implicitly auto wiring the service
if a class, which is configured as a Spring bean, has only one constructor, the Autowired annotation can be omitted and Spring will use that constructor and inject all necessary dependencies.
To sum up #AllArgsConstructor can/should be removed
A GenericServlet is a type of ServletConfig, also GenericServlet has a ServletConfig. What is logic in this? How should I understand this?
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
private static final long serialVersionUID = 1L;
private transient ServletConfig config;
..
}
The ServletConfig is an interface and is implemented by services in order to pass configuration information to a servlet when it is first loaded.
GenericServlet implements ServletConfig. It's not a subclass of ServletConfig. Understand the difference between a subclass and interface.
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides the implementation of all the methods of these interfaces except the service method.
GenericServlet class can handle any type of request so it is protocol-independent.
You may create a generic servlet by inheriting the GenericServlet class and providing the implementation of the service method.
Visit here for more
Is it ok to have an object inside of EAR like the Calculator class to be used as a utility for other stateless classes?
Is it a bad design? If so what appropriate approach should be applied?
#Stateless
class A{
public void sumForA(){
System.out.println("SUM IS : "+ (Calculator.getInstance().add(4+6)));
}
}
#Stateless
class B{
public void sumForB(){
System.out.println("SUM IS : "+(Calculator.getInstance().add(1+2)));
}
}
public class Calculator{
static{
INSTANCE=new Calculator();
}
private static INSTANCE;
public Calculator getInstance(){
return INSTANCE;
}
public int add(int x,int y){
return x+y;
}
}
First, there is no such name "static variable instance", there is instance variables and static variables, you can find an example here: Java Static vs Instance.
Second, regarding your Calculator class, you need to mark the getInstance() method as static beacause you are calling it directly. And, you seem trying to use the singleton pattern, I suggest you take a look at this SO question: What is an efficient way to implement a singleton pattern in Java?
Third, in your example there is no static variable in the statless bean, and to make it simple: you are only invoking a method in the Class Calculator which has static members. So why not?! you are using your utility class inside your method, it doesn't matter if it's a stateless bean or any kind of beans (EJB session beans, CDI / JSF beans, Spring Components ... ).
I am using monolog
in class DefaultController extends Controller
such as
$logger = $this->get('logger');
$logger->info('Get Started');
I can call this->get('logger') from the class which inherits Controller class.
However I want to use logger from other class such as /Entity/User.php
How can I make it?
my reference is
http://symfony.com/doc/2.0/cookbook/logging/monolog.html
In general you can access services like the logger in classes where the container is not automatically injected ( i.e. Controller and Commands extending ContainerAwareCommand ) by using Dependency Injection.
Possible injection-types are property-,setter- and constructor injection. My example will cover constructor injection. you will first need to create a service for your class.
Assuming yml-configuration an example could look like this:
services:
your_service:
class: Vendor/YourBundle/NonControllerExtendingClass
arguments: ["#logger"] # inject logger service into constructor
In my example the 'logger' service is automatically injected in the NonControllerExtendingClass if it is called as a service. Make sure you have something like this in your Vendor/YourBundle/NonControllerExtendingClass:
use Symfony\Component\HttpKernel\Log\LoggerInterface;
// ...
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
now use the logger in your method like this:
public function someAction()
{
$this->logger->info('Im here');
}
The logger will only be injected if you call your class as a Service or inject the logger manually.
// ... gets service from the container
$my_service = $this-container->get('your_service');
// ... manual injection
$logger = $this->container->get('logger');
// alternatively create a logger object yourself i.e. $logger = new Logger();
$my_service = new Vendor/YourBundle/NonControllerExtendingClass($logger);
If you want to track entity changes with the logger you should use a Doctrine Event Listener or Subscriber.
Readmore about it in the documentation chapter - How to Register Event Listeners and Subscribers.
Because of separation of concerns, entities should not have dependencies on services. Depending on your needs, it might be wise to use the logger from the controller/service or whatever that calls the entities method that you want to log.
Generally speaking, you can define classes as services and inject the logger into that service. If you are not yet familiar with the service container and dependency injection, I would strongly advise you to read this chapter of the docs.
It might be a tricky subject to grasp. However, as it is such a vital component of symfony, it will be really worth your while to try to understand this.
I have a Spring portlet controller class. In this class, there is a dependency like this:
#Autowired
protected ServiceClass someService;
#Autowired
protected ApplicationContext context;
From the controller, there is a utility class being called like this:
UtilityClass.loadStaticData((WebApplicationContext)context);
Inside UtilityClass, I have:
public static synchronized boolean loadStaticData(WebApplicationContext context){
ServiceClass someService = (ServiceClass) context.getBean("someService");
...
}
My question is: Is there any advantage to getting the handle of the someService in such a complicated way? We could have just passed the reference 'someService' from Controller class #1 to the UtilityClass. The author is no longer available so I am asking here.
This is basically what dependency injection tries to avoid: getting a dependency from the container instead of having the dependency injected by the container.
This utility class should be a Spring bean, where the service would be injected. And you could then inject this utility bean inside the controller.