How to get all spring managed bean
- 2021-11-14 05:34:39
- OfStack
Get all spring managed bean
In this article, we explore different ways to obtain all bean in the spring container.
IOC container
bean is the foundation of spring-based applications. All bean reside in the ioc container, which manages the bean lifecycle
There are two ways to get bean in a container:
-Use the ListableBeanFactory interface
-Use Spring Boot Actuator
Use the ListableBeanFactory interface
The ListableBeanFactory interface provides the getBeanDefinitionNames () method that returns all the names that define the bean. This interface is implemented by all factory and is responsible for preloading bean definitions to enumerate all bean instances. The official document provides all its sub-interfaces and their implementations.
The following example is built using Spring Boot:
First, we create some spring bean, and first define a simple Controller FooController:
@Controller
public class FooController {
@Autowired
private FooService fooService;
@RequestMapping(value="/displayallbeans")
public String getHeaderAndBody(Map model){
model.put("header", fooService.getHeader());
model.put("message", fooService.getBody());
return "displayallbeans";
}
}
This Controller relies on another spring Bean FooService:
@Service
public class FooService {
public String getHeader() {
return "Display All Beans";
}
public String getBody() {
return "This is a sample application that displays all beans "
+ "in Spring IoC container using ListableBeanFactory interface "
+ "and Spring Boot Actuators.";
}
}
We created two different bean:
1.
fooController
2.
fooService
Now let's run the application. Calling its getBeanDefinitionNames () method with an applicationContext object is responsible for returning all bean in the applicationContext context.
@SpringBootApplication
public class Application {
private static ApplicationContext applicationContext;
public static void main(String[] args) {
applicationContext = SpringApplication.run(Application.class, args);
displayAllBeans();
}
public static void displayAllBeans() {
String[] allBeanNames = applicationContext.getBeanDefinitionNames();
for(String beanName : allBeanNames) {
System.out.println(beanName);
}
}
}
Outputs all bean in the applicationContext context:
fooController
fooService
//other beans
Note that in addition to the bean we defined, it will print all the other bean in the container. For the sake of clarity, a lot has been omitted here.
Use Spring Boot Actuator
Spring Boot Actuator provides an endpoint for monitoring application statistics (endpoint). In addition to/beans, there are many other endpoints, which are detailed in the official documents.
Now we visit url: http//
:/beans, if no other standalone administrative port is specified, we use the default port and the result returns json, including all bean information defined by the container:
[
{
"context": "application:8080",
"parent": null,
"beans": [
{
"bean": "fooController",
"aliases": [],
"scope": "singleton",
"type": "com.baeldung.displayallbeans.controller.FooController",
"resource": "file [E:/Workspace/tutorials-master/spring-boot/target
/classes/com/baeldung/displayallbeans/controller/FooController.class]",
"dependencies": [
"fooService"
]
},
{
"bean": "fooService",
"aliases": [],
"scope": "singleton",
"type": "com.baeldung.displayallbeans.service.FooService",
"resource": "file [E:/Workspace/tutorials-master/spring-boot/target/
classes/com/baeldung/displayallbeans/service/FooService.class]",
"dependencies": []
},
// ...other beans
]
}
]
Of course, the results also include many other bean, which are not listed here for simplicity.
Summary 1
Returning all bean information defined in the spring container using the ListableBeanFactory interface and Spring Boot Actuators is described above.
Principle of spring Managing bean
By default, the Spring container parses the configuration file and instantiates all classes in the file when the service starts.
When using spring, the bean that gets spring injection looks like this
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
MyService myService1 = (MyService) ctx.getBean("myService");
Then let's simulate the process of spring managing bean
The code is as follows:
1. Step 1: Create java project and introduce spring. jar
2. Create an spring. xml configuration file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
</beans>
3. To create the interface MyService, only one test method save is needed
4. Create the implementation class MyServiceImpl, and the console outputs 1 sentence
5. Create your own parsing class MyClassPathXmlApplicationContext
Mainly two steps in the construction method
// Load instantiation bean
private Map<String, Object> beanMap = new HashMap<String, Object>();
// Load the properties and values of the configuration file
private List<MyBeans> beanlist = new ArrayList<MyBeans>();
public MyClassPathXmlApplicationContext(String filename) {
// No. 1 1 Step, parsing spring Configuration file
readXml(filename);
// No. 1 2 Step, instantiate all injections through reflection bean
initBeans();
}
/**
* Initializes the in the configuration file through reflection mechanism bean
*/
private void initBeans() {
for (MyBeans bean : beanlist) {
try {
if (bean.getClassName() != null && !"".equals(bean.getClassName())) {
beanMap.put(bean.getId(), Class.forName(bean.getClassName()).newInstance());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Parse the configuration file and put the parsed bean Set to the entity and keep it to list
*
* @param filename
*/
private void readXml(String filename) {
SAXReader reader = new SAXReader();
Document doc = null;
URL xmlpath = this.getClass().getClassLoader().getResource(filename);
try {
Map<String, String> nsMap = new HashMap<String, String>();
nsMap.put("ns", "http://www.springframework.org/schema/beans");
doc = reader.read(xmlpath);
XPath xpath = doc.createXPath("//ns:beans//ns:bean");// Create //ns:beans//ns:bean Query path
xpath.setNamespaceURIs(nsMap);// Set Namespace
List<Element> eles = xpath.selectNodes(doc);// Get all nodes under the document
for (Element element : eles) {
String id = element.attributeValue("id");
String cn = element.attributeValue("class");
// Custom Entity bean Save in the configuration file id And class
MyBeans beans = new MyBeans(id, cn);
beanlist.add(beans);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Object getBean(String beanId) {
return beanMap.get(beanId);
}
6. Entity classes
package com.mooing.service;
public class MyBeans {
private String id;
private String className;
public MyBeans(String id, String className) {
this.id = id;
this.className = className;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
STEP 7 Test
MyClassPathXmlApplicationContext ctx = new MyClassPathXmlApplicationContext("spring.xml");
MyService myService = (MyService) ctx.getBean("myService");
myService.save();
Summary 1
Custom code can also get the effect of using spring container instantiation, that is, when the actual spring instantiation manages bean, it also goes through two big steps:
1: The service starts to parse the configuration file and save the elements in the configuration file;
2: Instantiate all elements and provide methods to get instances.