In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you how to get all the bean managed by spring, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!
IOC container
Bean is the foundation of spring-based applications. All bean resides in the ioc container, and the container is responsible for managing the bean life cycle.
There are two ways to get the bean in the container:
-use the ListableBeanFactory interface
-use Spring Boot Actuator
Use the ListableBeanFactory interface
The ListableBeanFactory interface provides a getBeanDefinitionNames () method that returns all the names that define the bean. This interface is implemented by all factory and is responsible for preloading the bean definition to enumerate all bean instances. The official documentation provides all of its subinterfaces and their implementations.
The following example is built using Spring Boot:
First, let's create some spring bean, first defining a simple Controller FooController:
@ Controllerpublic 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";}}
The Controller relies on another spring Bean FooService:
Servicepublic 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. Use the applicationContext object to call its getBeanDefinitionNames () method, which is responsible for returning all the bean in the applicationContext context.
@ SpringBootApplicationpublic 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);}
All bean in the applicationContext context will be output:
FooController
FooService
/ / other beans
Note that in addition to the bean we defined, it will print all other bean in the container. For the sake of clarity, a lot has been omitted here.
Use Spring Boot Actuator
Spring Boot Actuator provides endpoints (endpoint) for monitoring application statistics. In addition to / beans, there are many other endpoints, which are detailed in the official documentation.
Now let's visit url: http//
: / beans. If no other independent management port is specified, we use the default port, and the result will return json, including all the defined bean information of 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.
Make a brief summary
The above describes the use of the ListableBeanFactory interface and Spring Boot Actuators to return all the defined bean information in the spring container.
The 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, get the bean injected by spring as follows: 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. The first step is to create java project and introduce spring.jar
two。 Create a spring.xml profile
3. To create the interface MyService, all you need is a test method, save
4. Create the implementation class MyServiceImpl, and output a sentence from the console
5. Create your own parsing class MyClassPathXmlApplicationContext
Mainly the two steps in the construction method.
/ / load instantiated bean private Map beanMap = new HashMap (); / / load the properties and values of the configuration file private List beanlist = new ArrayList (); public MyClassPathXmlApplicationContext (String filename) {/ / the first step is to parse the spring configuration file readXml (filename) / / the second step is to instantiate all injected bean initBeans () through reflection. } / * through the reflection mechanism Initialize bean * / private void initBeans () {for (MyBeans bean: beanlist) {try {if (bean.getClassName ()! = null & &! ".equals (bean.getClassName () {beanMap.put (bean.getId ()) in the configuration file Class.forName (bean.getClassName ()) .newInstance () }} catch (Exception e) {e.printStackTrace () } / * parse the configuration file, set the parsed bean 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 nsMap = new HashMap (); 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 the namespace List 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 id and class MyBeans beans = new MyBeans (id, cn) in the configuration file; beanlist.add (beans);}} catch (Exception e) {e.printStackTrace () }} public Object getBean (String beanId) {return beanMap.get (beanId);}
6. Entity class
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;}}
7. test
MyClassPathXmlApplicationContext ctx = new MyClassPathXmlApplicationContext ("spring.xml"); MyService myService = (MyService) ctx.getBean ("myService"); myService.save (); these are all the contents of the article "how to get all the bean managed by spring". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.