สร้าง@Configurationคลาสที่มีคำอธิบายประกอบ:
@Configuration
public class MyApplicationContext {
}
สำหรับแต่ละ<bean>แท็กให้สร้างเมธอดที่มีคำอธิบายประกอบ@Bean:
@Configuration
public class MyApplicationContext {
@Bean(name = "someBean")
public SomeClass getSomeClass() {
return new SomeClassImpl(someInterestingProperty); // We still need to inject someInterestingProperty
}
@Bean(name = "anotherBean")
public AnotherClass getAnotherClass() {
return new AnotherClassImpl(getSomeClass(), beanFromSomewhereElse); // We still need to inject beanFromSomewhereElse
}
}
ในการนำเข้าbeanFromSomewhereElseเราจำเป็นต้องนำเข้าคำจำกัดความ สามารถกำหนดได้ใน XML และเราจะใช้@ImportResource:
@ImportResource("another-application-context.xml")
@Configuration
public class MyApplicationContext {
...
}
ถ้า bean ถูกกำหนดใน@Configurationคลาสอื่นเราสามารถใช้@Importคำอธิบายประกอบ:
@Import(OtherConfiguration.class)
@Configuration
public class MyApplicationContext {
...
}
หลังจากที่เรานำเข้า XML หรือ@Configurationคลาสอื่น ๆแล้วเราสามารถใช้ถั่วที่พวกเขาประกาศในบริบทของเราได้โดยการประกาศสมาชิกส่วนตัวใน@Configurationคลาสดังนี้:
@Autowired
@Qualifier(value = "beanFromSomewhereElse")
private final StrangeBean beanFromSomewhereElse;
หรือใช้เป็นพารามิเตอร์โดยตรงในวิธีการที่กำหนด bean ที่ขึ้นอยู่กับสิ่งนี้beanFromSomewhereElseโดยใช้@Qualifierดังนี้:
@Bean(name = "anotherBean")
public AnotherClass getAnotherClass(@Qualifier (value = "beanFromSomewhereElse") final StrangeBean beanFromSomewhereElse) {
return new AnotherClassImpl(getSomeClass(), beanFromSomewhereElse);
}
คุณสมบัติการนำเข้าคล้ายกับการนำเข้า bean จาก xml หรือ@Configurationคลาสอื่นมาก แทนที่จะใช้@Qualifierเราจะใช้@Valueกับคุณสมบัติดังนี้:
@Autowired
@Value("${some.interesting.property}")
private final String someInterestingProperty;
สามารถใช้กับนิพจน์SpEL ได้เช่นกัน
ในการอนุญาตให้สปริงจัดการคลาสเช่นคอนเทนเนอร์ถั่วเราจำเป็นต้องทำเครื่องหมายสิ่งนี้ใน xml หลักของเราโดยใส่แท็กนี้ในบริบท:
<context:annotation-config/>
ตอนนี้คุณสามารถนำเข้า@Configurationคลาสได้เหมือนกับที่คุณสร้าง bean ง่ายๆ:
<bean class="some.package.MyApplicationContext"/>
มีหลายวิธีในการหลีกเลี่ยง Spring XMLs โดยสิ้นเชิง แต่ไม่ได้อยู่ในขอบเขตของคำตอบนี้ คุณสามารถค้นหาหนึ่งในตัวเลือกเหล่านี้ได้ในบล็อกโพสต์ซึ่งฉันใช้คำตอบของฉัน
โดยทั่วไปฉันพบว่าวิธีการประกาศถั่วนี้สะดวกสบายมากกว่าการใช้ XML เนื่องจากมีข้อดีบางประการที่ฉันเห็น: