javascript
Spring框架bean的注解管理方法之一 使用注解生成对象
首先在原有的jar包:
需Spring壓縮包中的四個核心JAR包
beans 、context、core 和expression
下載地址:
https://pan.baidu.com/s/1qXLHzAW
以及日志jar包
commons-logging 和log4j
下載地址:
https://pan.baidu.com/s/1mimTW5i
再增加一個
spring-aop-5.0.1.RELEASE.jar
增加注解功能的jar包名字是aop有些奇怪(不是annotation ,也不是context)
?
?
然后,src中建立一個xml配置文件,增加新的context的約束語句,如下:
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 開啟注解掃描 --><context:component-scan base-package="com.swift"></context:component-scan> </beans>注解的方法xml中配置對象及屬性只用這一句
<context:component-scan base-package="com.swift"></context:component-scan>
即可,com.swift是包名,最好寫上一級,可以掃描到里邊所有的包
下邊使用注解來創建對象:
package com.swift.user;import org.springframework.stereotype.Component;@Component(value="user") public class User {public String fun() {return "The User's fun()..........";} } ?注解創建對象
@Component(value="user")
或者
@Component
默認就是生成user對象
相當于之前在xml配置文件中使用<bean id="user" class="com.swift.User"></bean>
實際上除了可以用@Component 還可以用@Service @Controller @Repository ,功效一樣,分別預備service層 web層 dao層使用的
默認單例,如果要多例可以這樣寫
@Component(value="user")
@Scope(value="prototype")
關于value="prototype"?還有待補充
?struts2的Action使用多例 有成員變量的用多例 否則會引起多線程的并發
?
?
?
?
轉載于:https://www.cnblogs.com/qingyundian/p/7846098.html
總結
以上是生活随笔為你收集整理的Spring框架bean的注解管理方法之一 使用注解生成对象的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: nagios一键安装脚本
- 下一篇: Lesson 4- Exchange S