1. 需要在applicationContext.xml 启动注解注入的方式,添加配置选项,如下:
xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
完整的applicationContext.xml:
<?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:aop="http://www.springframework.org/schema/aop" 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.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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"/><!--自动搜索自定包下的类进行注解注入--> </beans>
2. 对类进行注解注入
如何对需要注解的类进行标识,分为两种方法:
(1). 通用方法:
@Component("别名")
@Scope("prototype") //多例(默认是单例)
通用方法对所有的类都可用,如action,service,dao,但是不推荐使用,因在这样不好区分,代码可读性不好。
(2).特殊类注解(这种方法是spring推荐的)
action 类: @Controller("别名")
service 类: @Service("别名")
dao 类: @Repository("别名")
3. 实例代码
UserAction:
package com.spring.action; import javax.annotation.Resource; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.spring.dao.UserDao; import com.spring.service.UserService; @Controller("userAction") @Scope("prototype") //多例模式 public class UserAction { @Resource(name="userService") //通过注解得到UserService对象 private UserService us; @Resource(name="UserDao") //通过注解得到UserDao对象 private UserDao dao; public void run(){ System.out.println("UserAction running......"); us.runService(); dao.addUser("admin"); } }
UserService:
package com.spring.service; import org.springframework.stereotype.Service; @Service("userService") public class UserService { public void runService(){ System.out.println("user service running......"); } }
UserDao:
package com.spring.dao; import org.springframework.stereotype.Repository; @Repository("UserDao") public class UserDao { public void addUser(String username){ System.out.println(username+"添加成功"); } }