Overriding a singleton with a scoped proxy - java

In Spring, is it possible to override a singleton bean definition with a scoped proxy?
Namely, if I have some
#Configuration
public class MyConfiguration
{
#Bean
public Foo foo()
{
return new Foo();
}
}
I want to create a test configuration but with a custom scope for "Foo":
#Configuration
public class MyTestConfiguration extends MyConfiguration
{
#Override
#Scope(value="myTestScope", proxyMode=ScopedProxy.TARGET_CLASS)
public Foo foo()
{
return new Foo();
}
}
However, this approach doesn't work! The constructed Foo is still a singleton! Unfortunately, adding #Primary and adding #Bean annotations to the test configuration doesn't help either. Is there any way to override a singleton with a scoped proxy?

The valid scopes values are :
singleton – Return a single bean instance per Spring IoC container
prototype – Return a new bean instance each time when requested
request – Return a single bean instance per HTTP request. session –
Return a single bean instance per HTTP session. globalSession –
Return a single bean instance per global HTTP session.

Related

Why in case of injecting CGLIB prototype into Singleton each access to prototype creates a new object?

Disclaimer:
I've read follownig heelpful staff about JDK dynamic proxy and CGLIB: https://stackoverflow.com/a/21762454/2674303
I''ve read following interesting article:Injecting Spring Prototype bean into Singleton bean
First case:
Prototype:
#Service
#Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
class MessageBuilder {
private static final AtomicInteger instanceCounter = new AtomicInteger(0);
MessageBuilder() {
instanceCounter.incrementAndGet();
}
static int getInstanceCounter() {
return instanceCounter.get();
}
....
}
Singleton:
#Service
class MessageService {
private final MessageBuilder messageBuilder;
MessageService(MessageBuilder messageBuilder) {
this.messageBuilder = messageBuilder;
}
Message createMessage(String content, String receiver) {
return messageBuilder
.withContent(content)
.withReceiver(receiver)
.build();
}
}
Test:
#RunWith(SpringRunner.class)
#SpringBootTest
public class MessageServiceTest {
#Autowired
private MessageService messageService;
#Test
public void shouldCreateTwoBuilders() throws Exception {
//when
messageService.createMessage("text", "alice");
messageService.createMessage("msg", "bob");
//then
int prototypeCounter = MessageBuilder.getInstanceCounter();
assertEquals("Wrong number of instances", 2, prototypeCounter);
}
}
Obviously test fails because injection happens only once and actual result will be 1 but we expected 2.
Second case:
Singleton and Test are the same but prototype now looks like this(proxyMode was changed):
#Service
#Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE,
proxyMode = ScopedProxyMode.TARGET_CLASS)
class MessageBuilder {
// ...
}
When we start our test we see that actual result is 6 because of inside createMessage method messageBuilder is accessed 3 times. and createMessage method is invoked twice so 3*2=6.
To explain behaviour author provided following picture:
I can't understand which bean is dependant and why each access to proxy messageBuilder genetares new bean instantiation. Why for first case the situation different ? Could you explain it ? As far I understand it - proxy are crated anyway - using CGLIB or using Dynamic proxy so anyway proxy is injected
If you define a bean with a prototype scope, a new instance is returned by the ApplicationContext when the bean is referenced from the Spring context. In your first example, a new instance of MessageBuilder prototype is created when the MessageService singleton bean is created. However, as the MessageService is constructed only once during the Spring lifecycle (as it is a singleton), it requests only one reference of the MessageBuilder prototype bean to be injected.
In other words, in your first example, the MessageBuilder bean is only instantiated once as it is injected (autowired) into the MessageService once. Method calls performed on the injected prototype bean will not be proxied to a new prototype bean instance afterwards.
By setting the proxyMode to TARGET_CLASS, the ApplicationContext does not directly inject a new prototype bean instance in another bean, but instead injects a proxy of the prototype bean. Thereby, when the singleton bean calls a method from the injected singleton bean, the intermediate proxy references a new prototype bean and calls the method.
More information can be found in the Spring documentation:
If you want to inject (for example) an HTTP request-scoped bean into another bean of a longer-lived scope, you may choose to inject an AOP proxy in place of the scoped bean. That is, you need to inject a proxy object that exposes the same public interface as the scoped object but that can also retrieve the real target object from the relevant scope (such as an HTTP request) and delegate method calls onto the real object.
https://stackoverflow.com/a/21762454/2674303 was the discussion about JDK dynamic proxy and CGLIB
article http://dolszewski.com/spring/accessing-prototype-bean-in-singleton/ was about how to inject prototype bean into a singleton bean
By definition of prototype scope, when you set prototype scope for MessageBuilder, you get a different object every time. You can verify ctx.getBean(MessageBuilder.class);
You want the same behavior when it is Autowired to a singleton bean. MessageService is singleton and only initialize once. If you inject a real MessageBuilder object to it, there is no way you get a different MessageBuilder object inside MessageService. So you will need to inject an aop proxy for MessageBuilder object. Spring can handle it correctly internally and gives you different object even though there is only one MessageService.

Getting Spring beans by method invocation vs new operator

I am confused about this little topic. Somewhere I read that if a class is annotated with #Component, it is spring managed bean and whenever it is required, spring will provide it. I am confusing it with scope of a bean. Let me explain:
Let's say a class
#Component
public class Example{ }
If I instantiate this class in other class using new Example(), would container always provide me the same Example object all the time? Or would it return me new object every time?
Here comes the confusing part:
If in the same class I have two beans like this:
#Component
public class Example {
#Bean DataSource sqlDataSource() {
// some logic
}
#Bean #Scope("prototype") SomeObject getSomeObject() {
return new SomeObject(sqlDataSource()); //**
}
}
What will happen in this case? sqlDataSource() method invocation would return the same object again and again every time SomeObject bean is requested, or new instance of DataSource will be returned every time SomeObject is requested?
#Bean is a method-level annotation that indicates Spring to create a bean when that method is invoked. It means to have the same functionality thatn tag in XML config.
This annotation must be used inside of a #Configuration annotated class, otherwise if you invoke the method from another method it will be a normal java new operation, not spring's. See this post --> #Bean inside class with #Configuration and witout it
Bearing this in mind new SomeObject(sqlDataSource()); would be equal to new SomeObject(new SqlDataSource());
if you annotate Example with #Configuration what will happen is that you'll get always a new SomeObject instance with the same sqlDataSource object, this means that Spring will take care of creating ONLY ONE sqlDataSource because it is singleton.
#Bean DataSource sqlDataSource() {
// some logic
}
This defines a singleton instance of DataSource. So everytime you request an instance of SomeObject a new SomeObject will be created (while it is defined in the prototype scope) but all of them will share the same DataSource object (since it's a singleton bean).

Spring boot bean into bean injection methodology

Can anyone tell me if there is a difference (in terms of spring bean injection and respecting singleton conditions or any other spring boot magic) in these two spring boot application classes?
#Bean
#Scope("singleton")
public UserService userService(Foo foo){
return new UserService(foo);
}
#Bean
#Scope("singleton")
public Foo foo(){
return new Foo();
}
AND calling not declaring Foo as a method parameter on userService() but rather injecting it via a direct method call to foo()
#Bean
#Scope("singleton")
public UserService userService(){
return new UserService(foo());
}
#Bean
#Scope("singleton")
public Foo foo(){
return new Foo();
}
No, there is no difference. One might think, you would get a new bean instance everytime you call foo() in that configuration class, but the way Spring works in that case is, it creates a proxy for that configuration class which intercepts all method calls. The proxy then checks, if there is already a bean of type Foo, if so it returns the existing instance, otherwise the method call is delegated to the implementation and a new bean is created.
Code style wise, however, i think in your first example the dependency to the Foo bean is more clearly marked than in the second example.

Why in Spring I am not allowed to annotate a final class with #Configuration?

I am studying for the Spring Core certification and I have some doubts related to the answer of this question founded on the study material stuff.
Why are you not allowed to annotate a final class with #Configuration
My reasoning is the following one for substantiate this assertion:
Consider the following configuration class:
#Bean
public AccountRepository accountRepository() {
return new JdbcAccountRepository();
}
#Bean
public TransferService transferService() {
TransferServiceImpl service = new TransferServiceImpl();
service.setAccountRepository(accountRepository());
return service;
}
#Bean
public AccountService accountService() {
return new AccountServiceImpl(accountRepository());
}
At first look this situation could appear strange because the first method (accountRepository()) instantiates an JdbcAccountRepository object as a bean having id=AccountRepository that, following the Spring default behavior, is a singleton
The second and the third method call twice more time the accountRepository() method that should instantiate twice more JdbcAccountRepository objects and this is not possibile because it is singleton !!!
So, to solve this situation Spring use the Inheritance-based Proxies strategy that expect to create a child class of my configuration class (the one annoted by #Configuration) and it is does:
For each bean, an instance is cached in the child class
Child class only calls super at first instantiation
So the child class is the entry point because the following behavior is implemented by this child class:
public class AppConfig$$EnhancerByCGLIB$ extends AppConfig {
public AccountRepository accountRepository() {
// if bean is in the applicationContext
// return bean
// else call super.accountRepository() and store bean in context
}
public TransferService transferService() {
// if bean is in the applicationContext, return bean
// else call super.transferService() and store bean in context
}
.....................................................
.....................................................
.....................................................
}
So if I annotate a configuration class with final Spring can't have this behavior because in Java a final class cannot be subclassed
Is it correct?
Using the same reasoning can I also assert that in Spring I can't have a final method annoted with #Bean annotation?
Because, as shown in the previous example, I have that when at startup time is created the child class (the proxy) of my configuration class happens that for each bean, an instance is cached in the child class and if it is final it is not possible (but I am absolutly not sure about this assertion)
Am I missing something? Can you give me the exact explaination?
Tnx
Spring creates dynamic proxies for classes annotated with #Configuration classes. Spring uses CGLIB to extend your class to create proxy. Hence, configuration classes cannot be final.
Regarding accountRepository() being invoked twice:
If you invoke accountRepository() method to create an instance, it is no more a Spring managed bean. Spring will not have any idea of the instances created in this manner. Hence, you will end up with multiple instances of JdbcAccountRepository
You can preserve the singleton behavior if you configure as below:
#Bean
public TransferService transferService(JdbcAccountRepository jdbcAcctRepo) {
TransferServiceImpl service = new TransferServiceImpl();
service.setAccountRepository(jdbcAcctRepo);
return service;
}
#Bean
public AccountService accountService(JdbcAccountRepository jdbcAcctRepo) {
return new AccountServiceImpl(jdbcAcctRepo);
}

#Bean inside class with #Configuration and without it

There is a #Bean annotation in Spring 3.0. It allows to define a Spring bean directly in a Java code. While browsing Spring reference I found two different ways of using this annotation - inside class annotated with #Configuration and inside class which doesn't have this annotation.
This section contains following piece of code:
#Component
public class FactoryMethodComponent {
#Bean #Qualifier("public")
public TestBean publicInstance() {
return new TestBean("publicInstance");
}
// omitted irrelevant method
}
And here we could see a very similar piece of code, but now #Configuration is in the place:
#Configuration
public class AppConfig {
#Bean
public MyService myService() {
return new MyServiceImpl();
}
}
Former section of reference contains following explaination:
The #Bean methods in a Spring component are processed differently than their counterparts inside a Spring #Configuration class. The difference is that #Component classes are not enhanced with CGLIB to intercept the invocation of methods and fields. CGLIB proxying is the means by which invoking methods or fields within #Configuration classes #Bean methods create bean metadata references to collaborating objects. Methods are not invoked with normal Java semantics. In contrast, calling a method or field within a #Component classes #Bean method has standard Java semantics.
But CGLIB is a kind of internal stuff which application developer shouldn't be aware of (in a ideal world, of course). As I understand in both cases Spring invokes method annotated with #Bean to create Spring bean, in both cases these instances are injected to collaborators.
So my question is what is the difference for me as an application developer between this two cases?
The difference is that with #Configuration you can call one #Bean method from another and get a fully initialized instance, as follows:
public class Foo {
#Value("Hello, world!")
public String value;
}
#Configuration
public class Config {
#Bean
public Foo createFoo() {
Foo foo = new Foo();
System.out.println(foo.value); // Prints null - foo not initialized yet
return foo;
}
#Bean
public Bar createBar() {
Foo foo = createFoo();
System.out.println(foo.value); // Prints Hello, world! - foo have been initialized by the interceptor
return new Bar(foo);
}
}
#Bean [instance method] inside #Component - One method with #Bean instance call other method #Bean instance , then it would be simple java semantics call i.e. Object won't returned by Spring container , It would be normal return from java instance factory method,because Component class don't extends CGLIB.
#Bean [instance method] inside #Configuration - In this case , spring container would be returning reference to exisiting object. It won't be normal java sematic call.
#Bean on static method inside Configuration & Component Class - In this case , #Bean method would never be intercepted by the container neither in Configuration class nor in Component Sterotype class.

Categories

Resources