Spring’s actual operation example of obtaining the ID of the bean itself
•
Java
This example describes the actual operation of spring to obtain the ID of the bean itself. Share with you for your reference, as follows:
One configuration
<?xml version="1.0" encoding="GBK"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <!-- spring容器会检测容器中所有Bean,如果发现某个Bean实现了BeanNameAware接口, spring容器会在创建该Bean之后,自动调用该Bean的setBeanName()方法, 调用该方法时,会将该Bean的配置id作为参数传给该方法 该方法的实现部分将Spring传入的参数(Bean的配置id)赋为给该Chinese对象的 beanName实例变量,因此接下来即可通过该beanName实例变量来访问Bean的配置id。--> <bean id="chinese" class="org.crazyit.app.service.Chinese"/> </beans>
Second bean
package org.crazyit.app.service; import org.springframework.beans.factory.BeanNameAware; public class Chinese implements BeanNameAware { // 保存部署该Bean时指定的id属性 private String beanName; public void setBeanName(String name) { this.beanName = name; } public void info() { System.out.println("Chinese实现类" + ",部署该Bean时指定的id为" + beanName); } }
Three test categories
package lee; import org.springframework.context.*; import org.springframework.context.support.*; import org.crazyit.app.service.*; public class SpringTest { public static void main(String[] args) { // 创建spring容器,容器会自动预初始化所有Bean实例 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); Chinese chin = ctx.getBean("chinese",Chinese.class); chin.info(); } }
IV. test results
Readers interested in more Java related content can view the topics on this site: introduction and advanced tutorial of spring framework, tutorial of Java data structure and algorithm, summary of Java DOM node operation skills, summary of java file and directory operation skills, and summary of Java cache operation skills
I hope this article will be helpful to you in Java programming.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码