Spring學習——註解方式基本配置Spring實體(含與xml配置對比)

  • 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>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章