除了基于 xml 的配置外,Spring 也支持基于 Annotation 的配置。Spring 提供以下介個 Annotation 來標(biāo)注 Spring Bean: @Component:標(biāo)注一個普通的 Spring Bean @Controller:標(biāo)注一個控制器組件類 @Service:標(biāo)注一個業(yè)務(wù)邏輯組件類 @Repository:標(biāo)注一個 DAO 組件類
基于 Annotation 配置的示例DAO 組件以@Repository 標(biāo)注:
public interface UserDao { public User getUserByUsername(String username);}@Repository("userDao")public class UserDaoImpl implements UserDao { List<User> users = new ArrayList<User>(); public UserDaoImpl() { users.add(new User(1001, "huey", "123")); users.add(new User(1002, "tmac", "abc")); users.add(new User(1003, "suer", "xxx")); } public User getUserByUsername(String username) { for (User user : users) { if (username.equals(user.getUsername())) { return user; } } return null; }}業(yè)務(wù)邏輯組件以@Service 標(biāo)注:
public interface UserServ { public User queryUserByUsername(String username); }@Service("userServ")public class UserServImpl implements UserServ { @Resource(name="userDao") private UserDao userDao; public User queryUserByUsername(String username) { return userDao.getUserByUsername(username); }}Spring 配置文件,無需配置 Bean,但須配置 <context:component-scan/>:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 自動掃描指定包及其子包下的所有 Bean 類 --> <context:component-scan base-package="com.huey.dream" /></beans>
測試方法:
@Testpublic void testAnnotation() throws Exception { applicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml"); UserServ userServ = appCtx.getBean("userServ", UserServ.class); String username = "huey"; User user = userServ.queryUserByUsername(username); System.out.println(user);}新聞熱點
疑難解答