2つの可能性が考えられます。
1つは(一種のハックです)、例のようにリンクする必要があるBeanがあまりない場合は、johnWorkをjohnHome Beanに注入し、johnHome.setPhoneで更新できますjohnWork の phone プロパティ、次のようなもの:
public class Contact {
private Contact myWorkContact;
private String phone;
public void setPhone(String phone) {
this.phone = phone;
if (this.myWorkContact != null) {
this.myWorkContact.setPhone(phone);
}
}
public void setWorkContact(Contact c) {
this.myWorkContact = c;
}
}
または、HomeContact と WorkContact の両方でクラス Contact を拡張し、それで同じインジェクションを行うこともできます。
これを必要とする大量の Bean がある場合 (アプリケーションが実際に連絡先情報を処理している場合など)、AOP (この例では AspectJ が必要です) を使用すると、このようなことができると思います (大量のオブジェクトを取得すると、少しメモリが集中しますが、そのようなものがどのように機能するかを見ることができます):
警告: これは実際にはすぐに複雑になりましたが、いくつかの問題を解決すればうまくいくと確信しています。
public class Contact {
...
private String phone;
private String name;
private Integer id;
public Contact(Integer id, String name, String phone) {
this.phone = phone;
this.name = name;
this.id = id;
}
public void setPhone(String phone) {
this.phone = phone.
}
//Other getters, setters, etc
...
}
@Aspect
public class ContactPhoneSynchronizer {
//there is probably a more efficient way to keep track of contact objects
//but right now i can't think of one, because for things like a tree, we need to
//be able to identify objects with the same name (John Smith), but that
//have different unique ids, since we only want one of each Contact object
//in this cache.
private List<Contact> contacts = Collections.synchronizedList(new ArrayList<Contact>());
/**
This method will execute every time someone makes a new Contact object.
If it already exists, return it from the cache in this.contacts. Otherwise,
proceed with the object construction and put that object in the cache.
**/
@Around("call(public Contact.new(Integer,String,String)) && args(id,name,phone)")
public Object cacheNewContact(ProceedingJoinPoint joinPoint, Integer id, String name, String phone) {
Contact contact = null;
for (Contact c : contacts) {
if (id.equals(c.getId()) {
contact = c;
break;
}
}
if (contact == null) {
contact = (Contact) joinPoint.proceed();
this.contacts.add(contact);
}
return contact;
}
/**This should execute every time a setPhone() method is executed on
a contact object. The method looks for all Contacts of the same
name in the cache and then sets their phone number to the one being passed
into the original target class.
Because objects are passed by reference until you do a reassociation,
calling c.setPhone on the object in the cache should update the actual
instance of the object in memory, so whoever has that reference will
get the updated information.
**/
@After("execution(example.Contact.setPhone(String) && args(phone)")
public void syncContact(JoinPoint joinPoint, String phone) {
Contact contact = joinPoint.getTarget();
for (Contact c : this.contacts) {
if (c.getName().equals(contact.getName()) {
c.setPhone(phone);
}
}
}
}
繰り返しますが、これを最適化できる方法はおそらく 100 通りあります。つまり、そもそもこのルートに行きたかった場合です。理論的には動作するはずですが、まったくテストしていません。
とにかく、ハッピースプリング!