除了基于 XML 的配置外,Spring 也支持基于 Annotation 的配置。Spring 提供以下介个 Annotation 来标注 Spring Bean:
@Component:标注一个普通的 Spring Bean
@Controller:标注一个控制器组件类
@Service:标注一个业务逻辑组件类
@Repository:标注一个 DAO 组件类
基于 Annotation 配置的示例
DAO 组件以 @Repository 标注:
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;
} }
业务逻辑组件以 @Service 标注:
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>
测试方法:
@Test
public 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);
}