Em còn 1 số điều mông lung vê việc sử dụng @Autowired
trong Spring. Mọi người giúp em cùng thảo luận để clear hơn nhé:
public interface AccountService {
public void createAccount();
}
public class AccountServiceImpl implements AccountService{
@Override
public void createAccount(){
// do something in here
}
}
@Controller
public class AccountController{
// Cách 1 dùng Autowired
@Autowired
AccountService actService;
// Cách 2 khai báo biến static
public static AccountService actService = new AccountService();
// Cách 3 khai báo biến cục bộ
private AccountService actService = new AccountService();
public void action(){
// Cách 4 khai báo biến bên trong hàm
AccountService actService = new AccountService();
actService.createAccount();
}
}
So với những cách còn lại thì việc sử dụng @Autowired
có gì khác biệt, lợi ích của việc sử dụng @Autowired
và khi nào thì mình nên sử dụng nó?
Nhờ các anh/chị giải đáp giúp em với nhé.