正文 Cat package org.example; public class Cat { public void eat(){ System.out.println("猫吃鱼干"); } } Dog package org.example; public class Dog { public void sleep(){ System.out.println("小狗睡大觉"); } } Animal package org.example; import org.springframework.beans.factory.annotation.Autowired; public class Animal { @Autowired private Cat cat; @Autowired private Dog dog; public Cat getCat() { return cat; } public void setCat(Cat cat) { this.cat = cat; } public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; } @Override public String toString() { return"Animal{"+"cat="+ cat +", dog="+ dog + '}'; } }
注意:要加上自动装配注解
set方法可以去掉也可以不用去掉
去掉的话如下图
package org.example; import org.springframework.beans.factory.annotation.Autowired; public class Animal { @Autowired private Cat cat; @Autowired private Dog dog; public Cat getCat() { return cat; } public Dog getDog() { return dog; } @Override public String toString() { return"Animal{"+"cat="+ cat +", dog="+ dog + '}'; } }
beans.xml 测试 package org.example; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test9 { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Animal animal=(Animal) context.getBean("animal"); animal.getCat().eat(); animal.getDog().sleep(); } }