Skip to content

Commit 1f864a1

Browse files
committed
Add example for registering an existing object as a singleton bean in Spring Core docs
Signed-off-by: Elbialy0 <[email protected]>
1 parent 1653ec3 commit 1f864a1

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

framework-docs/modules/ROOT/pages/core/beans/definition.adoc

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,54 @@ supports this registration through the `registerSingleton(..)` and `registerBean
6363
methods. However, typical applications work solely with beans defined through regular
6464
bean definition metadata.
6565

66+
[[beans-factory-register-singleton]]
67+
=== Registering an Existing Object as a Singleton Bean
68+
69+
In some cases, you might need to register an object that was created outside of the Spring container as a bean. You can achieve this using the `ConfigurableListableBeanFactory`:
70+
71+
[source,java]
72+
----
73+
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
74+
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
75+
76+
public class DynamicBeanRegistrationExample {
77+
78+
public static void main(String[] args) {
79+
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
80+
81+
// Refresh context (required before accessing BeanFactory)
82+
context.refresh();
83+
84+
// Create an object outside Spring
85+
MyService myService = new MyService("Hello from custom object!");
86+
87+
// Get BeanFactory and register the object as a singleton bean
88+
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
89+
beanFactory.registerSingleton("myServiceBean", myService);
90+
91+
// Retrieve the bean from the context
92+
MyService bean = context.getBean("myServiceBean", MyService.class);
93+
System.out.println(bean.getMessage());
94+
95+
context.close();
96+
}
97+
98+
static class MyService {
99+
private final String message;
100+
101+
public MyService(String message) {
102+
this.message = message;
103+
}
104+
105+
public String getMessage() {
106+
return message;
107+
}
108+
}
109+
}
110+
----
111+
This approach is useful when integrating legacy code or dynamically adding beans at runtime.
112+
113+
66114
[NOTE]
67115
====
68116
Bean metadata and manually supplied singleton instances need to be registered as early

0 commit comments

Comments
 (0)