1.如果希望為靜態(tài)內部類配置bean定義饭尝,則必須使用內部類的二進制名谋作。
例如乎芳,如果你的com.example包中有一個類名為Outer。這個類有一個靜態(tài)的內部類叫做Inner, 則bean定義上的class屬性的值是com.example.Outer$Inner, 注意吭净,在名稱中使用$字符將內部的類名與外部類名分隔開.
Outer.java
package chending;
/**
* @Description:
* @author: chenDing
* @date: 2020/2/28 20:50
*/
public class Outer {
public Outer() {
System.out.println("Outer對象被創(chuàng)建了");
}
public static class Inner {
public Inner() {
System.out.println("Inner 對象被創(chuàng)建了");
}
}
}
beans.xml
<?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.xsd">
<bean id="inner" class="chending.Outer$Inner"/>
</beans>
TestDemo.java
package chending.dao;
import chending.Outer;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @Description:
* @author: chenDing
* @date: 2020/2/28 20:53
*/
public class TestDemo {
@Test
public void testDemo() {
ClassPathXmlApplicationContext cpa = new ClassPathXmlApplicationContext("beans.xml");
// Outer.Inner inner = (Outer.Inner)cpa.getBean("inner");
Outer.Inner inner = cpa.getBean("inner", Outer.Inner.class);
System.out.println(inner);
}
}
以上配置正確會得到如下結果:
Inner 對象被創(chuàng)建了
chending.Outer$Inner@9a7504c
Process finished with exit code 0