了解过IoC的概念,没有真正实践,感觉还是会比较模糊。自己的实践虽然简单,但还是记录下呀~
1. 通过注解的方式注入service
1.1 controller中创建对象
@Controller
@RequestMapping("/account")
public class AccountController { private AccountService accountService; @Autowired
public void setAccountService(AccountService accountService){
this.accountService = accountService;
} ...
}
在调用service的地方,通过注释创建service对象。
1.2 定义service接口类
public interface AccountService {
Account getAccountById(Integer accountId);
...
}
1.3 实现service接口类
@Service("accountService")
public class AccountServiceImpl implements AccountService{ @Override
public Account getAccountById(Integer accountId) {
Account account = new Account();
account.setAccountId(accountId);
...
return account;
}
这样,就可以实现Service类的注入了。
2. 通过注释的方式注入Dao
2.1 定义Dao接口的实现类
@Repository("baseDao")
public class BaseDaoImpl implements BaseDao {
...
}
这是我的dao。
2.2 在service中调用创建Dao接口(类型为BaseDaoImpl) 实例
public class BaseServiceImpl implements BaseService { public BaseDao baseDao;
@Autowired
public void setBaseDao(){
...
}
...
}