Spring标注(Annotation)的使用
spring Annotation标注的配置:需要在beans的头部加入命名空间:
xmlns:context="http://www.springframework.org/schema/context"
?????????? http://www.springframework.org/schema/context
?????????? http://www.springframework.org/schema/context/spring-context-2.5.xsd"
加入标注
<context:annotation-config />
@Resource需要导入common-annotation.jar
?
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
?????? xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
?????? xmlns:context="http://www.springframework.org/schema/context"
?????? xsi:schemaLocation="http://www.springframework.org/schema/beans
?????????? http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
?????????? http://www.springframework.org/schema/context
?????????? http://www.springframework.org/schema/context/spring-context-2.5.xsd">
?
?<context:annotation-config />
??? <context:component-scan base-package="com" /><!-- 让spring在com包下自己去找bean -->
</beans>
?
dao层:
package com.dao;
import org.springframework.stereotype.Component;
import com.model.User;
@Component("userDao")
public class UserDaoImpl implements UserDao {
?public void save(User user) {
??//Hibernate
??//JDBC
??//XML
??//NetWork
??System.out.println(" user save !");
?}
}
?
service层:
package com.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import com.dao.UserDao;
import com.model.User;
@Component("userService")
public class UserServiceImpl implements UserService {
?private UserDao userDao;
?public void add(User user) {
??userDao.save(user);
?}
?public UserDao getUserDao() {
??return userDao;
?}
?@Resource(name="userDao")
?public void setUserDao(UserDao userDao) {
??this.userDao = userDao;
?}
?
}
测试代码:
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.model.User;
import com.service.UserService;
public class TestSpringIoc {
?
?public static void main(String[] args) {
??ApplicationContext? context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
?? User user = new User();
????? user.setPassword("sss");
????? UserService service = (UserService)context.getBean("userService");
????? service.add(user);
?}
}
注意:SpringAnnotation.rar中式源码和jar包