1、在构造器中注入新类和在构造器中注入基本参数类似,主要是修改xml里面的配置。
2、核心spring.xml文件
<bean id="do" class="com.test.pro.Student"> <constructor-arg value="19"></constructor-arg> <constructor-arg ref="read"></constructor-arg><!-- 这里是用构造器注入新类 --> </bean> <bean id="read" class="com.test.pro.Reading"> </bean>
3、Reading.java
package com.test.pro; public class Reading { public void doing() { System.out.println("我在读书......"); } }
4、测试类
package com.test.pro; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml"); Student did=(Student)ctx.getBean("do"); did.speaking(); } }
5、输出结果
时间: 2024-10-13 04:11:04