What is the meaning of '$' in toString() of a class? - tostring

I have a stateful Session bean named 'UserWS'. In the constructor of 'UserWS' I write toString() of the class.
public UserWS() {
System.out.println("In constructor:" + this.toString());
}
Some points are not clear to me:
At the first time I call a method of that class, the constructor called for 6 times. Why? I've expect it called just once. these are constructor calls:
In constructor: ws.UserWS$Proxy$_$$_WeldClientProxy#22c9b87b
In constructor: ws.UserWS$Proxy$_$$_Weld$EnterpriseProxy$#50933ff8
In constructor: ws.UserWS#303709bb
In constructor: ws.UserWS$$$view2#6872a8eb
In constructor: ws.UserWS$$$view2#4e75aedd
In constructor: ws.UserWS#53c4e19d
What is the meaning of '$' or '$Proxy' in result of toString() of a class?

When a Java framework like EJB or CDI is used with a class you write, the framework has to generate extra classes, based on yours, that provide the services like Injection, Security or Transactions. Often these will be something like a Proxy that intercepts a method request from your client code, adds the extra service and then calls the method in your original class.
In your output you have 2 actual calls to the constructor of your UserWS class and the remainder are the generated classes which have constructors at least partially copied from your UserWs constructor. The '$' is just part of the convention Weld is using to name those classes.
You can find more details of how they are generated by Weld here

Related

Springboot #GetMapping method injection with object as parameter

I am new to Spring Boot. As I understand how constructor injection works then I can't tell why HelloController works - index method is not a constructor so where/why cat object instance is created? Would be glad to get some documentation or articles about it.
HelloController.java
#RestController
public class HelloController {
#GetMapping("/{name}")
public String index(#PathVariable("name") String name, Cat cat){
cat.setName(name);
return "<b>Hello " + cat.getName() + "</b>";
}
}
Cat.java
#Component
public class Cat {
#Getter #Setter
private String name;
public Cat(){
System.out.println("Created new Cat!");
}
}
This is an interesting question - only because of the way you have put it. By injection, do you mean creation of a singleton class (You have Cat marked as #Component)? Well to answer this, I added something extra to your print statement:
public Cat(){
System.out.println("Created new Cat! with hasCode: " + hashCode());
}
You see, the hashCode should not change for the same object. The results are not very surprising:
Created new Cat! with hasCode: 362563829
Created new Cat! with hasCode: 782885695
The first line was printed when the application was started. That is expected as the bean is created with a scope of singleton and the process completes before the application is completely loaded. The second output comes when I make a request to the endpoint in which case, Spring creates an instance of Cat and passes it as an argument to the #GetMapping. You get as many objects of Cat as your requests.
Along the same lines, if i remove #Component from Cat, the first line does not show up.
Moving along, I made another change to the RestController class:
#RestController
public class HelloController {
#Autowired
private Cat myCat;
#GetMapping("/{name}")
public String index(#PathVariable("name") String name, Cat cat){
cat.setName(name);
System.out.println("Hello " + myCat.hashCode());
return "Hello " + cat.getName() + "The age is: " + cat.getAge();
}
}
Here is the result of running this application:
What it shows is that the cat passed on to the controller method is not same as the one that was managed by Spring container.
Concussions
Rest controller method will be passed a new instance of a class everytime it is called.
The controller method is not pass the instance of a spring managed object
N.B.: I have not really come across any official documentation statinng above findings. Would be very happy to see one though
Bean is an object managed by the Spring context. Objects of these classes do not need to be created - Spring is responsible for that. The developer can point to a place where such an object can be deployed. This action is called "dependency injection."
Simply put, Spring is smart enough that while you mark the class with the appropriate annotation, he takes care of the rest :)
There are plenty of articles on this topic just use google "how objects are created in Spring."
In Spring, it is possible to define a bean in several ways, by: By using annotations, Appointing their instances in the methods of the configuration class, Using XML configuration.
There are a number of annotations to create a bean. Each has its own destiny. The most popular annotations include: Component, Service, Repository, Controller / RestController

Multiple Constructor injection using Java Annotations

The SPRING doc says the following
Spring Framework 4.3, an #Autowired annotation on such a constructor
is no longer necessary if the target bean only defines one constructor
to begin with. However, if several constructors are available, at
least one must be annotated to teach the container which one to use.
As i understand if there are multiple constructors and we have not annotated any of them then i will get an error . I ran the following code
#Component // this is bean id
public class TennisCoach implements Coach {
private FortuneService fortuneservice;
public TennisCoach(FortuneService thefortuneservice) {
System.out.println(" inside 1 arg constructter");
fortuneservice = thefortuneservice;
}
public TennisCoach() {
System.out.println(" inside 0 arg constructter");
}
I call that using the below code
TennisCoach theCoach = myapp.getBean("tennisCoach", TennisCoach.class);
But i didn't get the error .I got the O/P as
inside 0 arg constructter
Why?
It looks like the text you've quoted from the Spring docs doesn't apply to a case where one of the constructors is a no-args (default) constructor. You can see this very easily if you try and add an bean reference parameter to it.
Spring attempts to determine the candidate constructors using AutowiredAnnotationBeanPostProcessor and in your scenario, will not find any single or autowired constructor, so it will record the no-args one and instantiate it in SimpleInstantiationStrategy.

Spring return dynamic instance based of String value

Java Spring question:
I have a interface MyInterface with one method
void exec (String str);
I have many implementation of MyInterface, say Oneimpl, anotherimpl yetanotherimpl...and so on and can keep adding new implementations.
how do I obtain an instance of a specific implementation using just the name of the implementing class passed as a STRING value , say "someRandomImpl"
The code should be dynamic and can provide a instance of new implementations without code change.
implements ApplicationContextAware
it will autowired ApplicationContext object
use the object like
context.getBean(beanName)
then you get the bean

Using Singleton enum in Spring MVC

Here is my singlton class using enum:
public enum MyInstanceFactory {
INSTANCE;
private SOMEOBJECT;
private int countInitialization = 0;
private MyInstanceFactory(){
countInitialization++;
System.out.println("WOW!! This has been initialized: ["+countInitialization+"] times");
SOMEOBJECT = SOMETHING
}
public Session getSomeobject(){ return SOMEOBJECT; }
}
Now I am calling it like inside MVC controller
Session cqlSession = MyInstanceFactory.INSTANCE.getSomeobject();
In this way it calls constructer only first time and next and onwards it return the correct value for SOMEOBJECT.
My question is I want to do the same thing when a spring application start i.e. initializing contructor once and use **getSomeobject** multiple times.
I saw THIS SO ANSWER but here they are saying
If it finds a constructor with the right arguments, regardless of visibility, it will use reflection to set its constructor to be accessible.
Will reflection create problem for a singlton class?
If you need a non-subvertible singleton class (not just a singleton bean that's shared by many other beans, but actually a singleton class where the class can only ever be instantiated once), then the enum approach is a good one. Spring won't try to instantiate the enum itself, because that really makes no sense; that would be a much more extremely broken thing to do than merely calling a private constructor.
In that case, to refer to the enum instance from Spring configuration, you do the same thing as for any other static constant; for example:
<util:constant static-field="MyInstanceFactory.INSTANCE" />

Spring configuration calling more than one method

I have code which looks like the following:
MyContext context = new MyContext();
context.start();
MyEntity entity = context.getEntity();
I want to inject the MyEntity instance into various classes.
But I don't know how to setup my Spring configuration, where I first create an object, then call a method on it and then finally call another method which returns the entity I want to inject.
EDIT 2 - removed the Strings altogether
The most common type of dependencies injected using Spring don't depend on the user input for their construction. This includes data access objects, services etc.,
You are talking about injecting domain objects whose construction depends on the user input either directly or indirectly.
Spring provides #Configurable annotation to inject such domain objects that are created using new operator. You can search for "#Configurable Domain Driven Design" on the internet to get examples of how this can be implemented. I myself used it in one my applications and wrote a simple post here that might help you get started.
Edit:
To create a bean of type MyEntity as per the specification in your updated question, you would need to
define a bean of type MyContext
Create a MyEntityFactory class that would depend on the MyContext bean.
The factory method would take the MyContext bean as argument, calls context.start() on it and returns an instance of MyEntity.
You would define the MyEntity bean using this factory class.
The MyEntityFactory class would be as follows:
public class MyEntityFactory
{
public static MyEntity getMyEntity(MyContext context)
{
context.start();
return context.getEntity();
}
}
The spring bean configuration will be as follows:
<bean id="myContext" class="FQCN.Of.MyContext" />
<bean id="myEntity" class="FQCN.Of.MyEntityFactory" factory-method="getMyEntity">
<constructor-arg ref="myContext" />
</bean>
Since MyEntity is a singleton bean, the factory method will be called only once, btw.
More on creating beans using factory methods here.

Resources