Spring inner Beanの例
Springフレームワークでは、Beanが1つの特定のプロパティのみに使用される場合は常に、内部Beanとして宣言することをお勧めします。 また、内部Beanは、セッターインジェクション ‘property‘とコンストラクターインジェクション ‘constructor-arg‘の両方でサポートされています。
Spring内部Beanの使用方法を示す詳細な例を参照してください。
package com.example.common;
public class Customer
{
private Person person;
public Customer(Person person) {
this.person = person;
}
public void setPerson(Person person) {
this.person = person;
}
@Override
public String toString() {
return "Customer [person=" + person + "]";
}
}
package com.example.common;
public class Person
{
private String name;
private String address;
private int age;
//getter and setter methods
@Override
public String toString() {
return "Person [address=" + address + ",
age=" + age + ", name=" + name + "]";
}
}
多くの場合、 ‘ref‘属性を使用して、「Person」Beanを「Customer」Bean、personプロパティに次のように参照できます。
一般に、このように参照することは問題ありませんが、「example」のperson BeanはCustomerBeanにのみ使用されるため、次のようにこの「example」のpersonを内部Beanとして宣言することをお勧めします。
この内部Beanは、次のようにコンストラクター注入でもサポートされます。
Note
BeanクラスのIDまたは名前の値は内部Beanでは必要ありません。これは、Springコンテナによって単に無視されます。
それを実行します
package com.example.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
Customer cust = (Customer)context.getBean("CustomerBean");
System.out.println(cust);
}
}
出力
Customer [person=Person [address=address1, age=28, name=example]]