我们需要使用@Component注解来定义一个配置类,在配置类中我们定义Bean:
package com.moonlit.myspring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MoonlitConfig { @Bean public Weapon halberd() { return new Halberd(); } @Bean public Hero guanyu() { GuanYu gy = new GuanYu(); gy.setWeapon(halberd()); return gy; } }
这里的GuanYu类如下:
package com.moonlit.myspring; public class GuanYu implements Hero { private Weapon weapon; public void perform() { System.out.println("Guan Yu pick up his weapon."); weapon.attack(); } public Weapon getWeapon() { return weapon; } public void setWeapon(Weapon weapon) { this.weapon = weapon; } }
然后我们就可以使用这个基于@Bean注解的bean了,下面的测试类用于演示效果:
package com.moonlit.practice; import com.moonlit.myspring.Hero; import com.moonlit.myspring.MoonlitConfig; public class TestPractive { public static void main(String[] args) { Hero hero = new MoonlitConfig().guanyu(); hero.perform(); } }
输出效果如下:
Guan Yu pick up his weapon.
halberd is attacking!!!