版权声明: https://blog.csdn.net/hu18315778112/article/details/84928040
-
1、开启使用注解配置
<!-- base-package="指定包路径" -->
<context:component-scan base-package="com.hh"></context:component-scan>
-
2、在类中使用注解配置:
- 1》将对象注册到容器
// 将此类注册到Spring容器,name="testAction" @Component("testAction") // 设置此类对象为多例模式 @Scope("prototype") public class TestAction extends ActionSupport{ }
上面注解相当于下面的xml配置:
<bean name="testAction" class="com.hh.test.TestAction" scope="prototype"></bean>
还有三个注解与Component注解作用完全相同,只不过使用单词来方便识别是哪一层的对象:
- @Service——服务——service层
- @Controller——控制中心——web层
- @Repository——知识库——dao层
- 2. 属性注入:
- 值类型:
// 将 12 注入到属性age中——通过反射的方式 @Value("12") private Integer age; // 将 12 注入到属性age中——通过set方法注入 @Value("12") public void setAge( Integer age ){ this.age=age; }
以上两种值类型属性注入方式,相当于一下xml配置:
<!-- 其中name="对象中的属性名";value"想要设置的属性值" --> <property name="age" value="12"></property>
- 引用类型注入
1. 想将要引用的对象配置到容器:
@Service("testService") public class TestServiceImpl implements TestService { }
2. 在类中使用注解将要引用的对象配置进来:
// name="要引用的对象配置到容器中的name值" @Resource(name="testService") private TestService testService;
@Resource(name="testService")还想到与以下两个注解同时使用:
- @Autowired
- @Qualifier("testService")
以上两步引用类型注解配置想到与以下xml配置:
<!-- 配置管理Service层测试类 --> <bean name="testService" class="com.hh.service.impl.TestServiceImpl"></bean> <!-- 配置Spring管理Action,注意:Action类一定配成多例:prototype --> <bean name="testAction" class="com.hh.test.TestAction" scope="prototype"> <property name="testService" ref="testService"></property> </bean>