1、DAO層(存儲層)要用@Repository註解,Service層(業務層)用@Service,Control層(展示層)用@Controller
2、@Autowired註釋。
引入了 @Autowired
註釋,它可以對類成員變量、方法及構造函數進行標註,完成自動裝配的工作。不需要再生成set和get方法。
@Service("studentService")
@Transactional
public class StudentServiceImpl implements StudentService{
@Autowired
private StudentDAO studentDao;
}
@Service("studentService")
@Transactional
public class StudentServiceImpl implements StudentService{
private StudentDAO studentDao;
@Autowired
public void setStudentDao(StudentDAO studentDao) {
this.studentDao = studentDao;
}
}
3、@Qualifier
@Autowired是根據類型進行自動裝配的。在上面的例子中,如果當Spring上下文中存在不止一個UserDao類型的bean時,就會拋出BeanCreationException異常;如果Spring上下文中不存在UserDao類型的bean,也會拋出BeanCreationException異常。我們可以使用@Qualifier配合@Autowired來解決這些問題。 Spring會找到id爲userDao的bean進行裝配。
@Autowired
public void setUserDao(@Qualifier("userDao") UserDao userDao) {
this.userDao = userDao;
}
4、@Resource
@Resource的作用相當於@Autowired,只不過@Autowired按byType自動注入,而@Resource默認按byName自動注入罷了。@Resource有兩個屬性是比較重要的,分別是name和type,Spring將@Resource註解的name屬性解析爲bean的名字,而type屬性則解析爲bean的類型。所以如果使用name屬性,則使用byName的自動注入策略,而使用type屬性時則使用byType自動注入策略。如果既不指定name也不指定type屬性,這時將通過反射機制使用byName自動注入策略。
5、@PostConstruct(JSR-250)
在方法上加上註解@PostConstruct,這個方法就會在Bean初始化之後被Spring容器執行(注:Bean初始化包括,實例化Bean,並裝配Bean的屬性(依賴注入))。
它的一個典型的應用場景是,當你需要往Bean裏注入一個其父類中定義的屬性,而你又無法複寫父類的屬性或屬性的setter方法時,如
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
private SessionFactory mySessionFacotry;
@Resource
public void setMySessionFacotry(SessionFactory sessionFacotry) {
this.mySessionFacotry = sessionFacotry;
}
@PostConstruct
public void injectSessionFactory() {
super.setSessionFactory(mySessionFacotry);
}
...
}
6、使用<context:annotation-config />簡化配置
7、 使用<context:component-scan />讓Bean定義註解工作起來
8、使用@Scope來定義Bean的作用範圍
@Scope("session")
@Component()
public class UserSessionBean implements Serializable {
...
}