在Spring 中,@Repository、@Service 、@Controller和 @Component 是等效的,都是将类自动注入。
spring引入了组件自动扫描机制,在类路径底下寻找标注了@Repository、@Service 、@Controller、@Component 注解的类,并把这些类纳入进spring容器中管理。
@Repository | @Service | @Controller | @Component |
持久层 | 业务层 | 控制层(web层) | 泛指组件 |
用于标注数据访问组件,即DAO层 | 用于标注业务层组件,实现类(该实现类继承抽象类或实现DAO接口) | 如struts中的action,? 用于抽象类 | 当组件不好归类时使用,用于比较中立的类 |
注入方式:
把DAO实现类注入到service实现类中,把service的接口(非service实现类)注入到action中,注入时不要new这个注入的类,因为spring会自动注入,如果手动再new的话会出现错误。
属性加上@Autowired后不需要getter()和setter()方法,spring也会自动注入。
@Autowired
AppCartService appCartService;
在接口前面标上@Autowired注释使得接口可以被容器注入。
@Autowired
protected GeneralDaoHelper generalDaoHelper;
@Autowired
protected CartMapper cartMapper;