Let’s consider 2 widely famous spring examples:
1. Local method call for @Transactional
public class UserService {
@Transactional
public boolean addUserTransactional(String userName, String password) {
try {
// call DAO layer and adds to database.
} catch (Throwable e) {
TransactionAspectSupport.currentTransactionStatus()
.setRollbackOnly();
}
}
public boolean addUsers(List<User> users) {
for (User user : users) {
this.addUserTransactional(user.getUserName, user.getPassword);
}
}
}
Here transaction won’t be started because addUserTransactional
will be called locally using this reference. So proxy magic won’t be in game because there is no proxy when we uset this reference.
Solution is moving the method to separated service, autowire it.
public class UserService {
@Autowired
private UserTransacionalService uts;
public boolean addUsers(List<User> users) {
for (User user : users) {
uts.addUserTransactional(user.getUserName, user.getPassword);
}
}
}
At this case uts.addUserTransactional(user.getUserName, user.getPassword)
will go via proxy so transaction will be started
2. Prototype injection into singleton
One way to inject protitype to singletons is:
Prototype definition:
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode=TARGET_CLASS)
public class Bank {
private final String bankName;
public Bank() {
this.bankName = UUID.randomUUID().toString();
System.out.println("new bank created");
}
public String getInput() {
return bankName;
}
}
inject it to the service:
@Service
public class BankService {
@Autowired
Bank bank;
public Bank foo(){
return bank.bar();
}
}
Here
Every time foo
method is called – new instance of bank
will be called
And expalanation of this behaviour that proxy(!!!) of bank
is autowired to BankService
although usually we autowire real beans.
I see contradiction here. First example demonstrates that we autowire proxy even without
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode=TARGET_CLASS)
Could you please clarify this in more details ? Are there multiple levels of proxy ?