Spring常用的的注解對應xml配置詳解

@Component(value="")注解:組件

  1. 標記在類上,也可以放在接口上
  2. 注解作用:把AccountDao實現類對象交由Spring IOC容器管理
    相當于XML配置文件中的Bean標簽
<bean id="userAnnonMapper" class="com.spring.mapper.UserAnnonMapperImpl"></bean>
  1. 注解Value屬性:相當于bean標簽id,對象在IOC容器中的唯一標識,可以不寫,默認值是當前類首字母縮寫的類名。注入時需要注意此名稱!!。
  2. 三個衍射注解分別是:@Controller,@Service,@Repository。
    作用與@Component注解一樣
    設計初衷增加代碼的可讀性,體現在三層架構上
    @Controller一般標注在表現層
    @Service一般標注在業務層
    @Repository一般 標注在持久層

注意:此注解必須搭配掃描注解使用

@Configuration 
@ComponentScan("com.*") 
public class SpringConfig{}

或 XML配置

<context:component-scan base-package="com.*"></context:component-scan>

進行注解掃描。
?

@Autowired注解:byType自動注入

  1. 標記在成員變量或set方法上
  2. 注解作用:自動將ioc容器中的對象注入到當前的成員變量中。
    默認按照變量數據類型注入,如果數據類型是接口,注入接口實現類。
    相當于XML配置文件中的property標簽
<property name="accountDao" ref="accountDao"/>
  1. 按照變量的數據類型注入,它只能注入其他的bean類型
  2. 注意事項:
    成員變量的接口數據類型,有多個實現類的時候,要使用bean的id注入,否則會報錯。
    Spring框架提供的注解
    必須指定Bean的id,使用@Qualifier的注解配合,@Qualifier注解的value屬性指定bean的id

舉例

@Component("userAnnonService02") 
public class UserAnnonServiceImpl01 implements UserAnnonService {} @Component("userAnnonService01") 
public class UserAnnonServiceImpl02 implements UserAnnonService {}

使用需要注意,因為一個接口被兩個實現類實現,所以根據屬性已經失效了使用@Qualifier選擇要注入的實現類

public class Test{    @Autowired    @Qualifier("userAnnonService01")    UserAnnonService userAnnonService;    
}    

其他補充

<bean id="userService" class="com.spring.service.UserServiceImpl">    <property name="userMapper" ref="userMapper"></property> 
</bean> <bean id="userMapper" class="com.spring.mapper.UserMapperImpl"></bean>

等價于注解開發的

@Component("userService") 
public class UserServiceImpl implements UserService {     @Autowired     UserAnnonMapper userAnnonMapper; 
}@Component("userAnnonMapper")
public class UserMapperImpl implements UserMapper {}

這里是我認為初學者比較容易搞混的地方。
?

@Resource(name="") byName注解(jdk提供)

  1. 標記在成員變量或set方法上
  2. 注解作用:相當于@Autowired的注解與@Qualifier的注解合并了,直接按照bean的id注入。
    相當于XML配置文件中的property標簽
<property name="accountDao" ref="accountDao"/>
  1. name屬性:指定bean的id
  2. 如果不寫name屬性則按照變量數據類型注入,數據類型是接口的時候注入其實現類。如果定義name屬性,則按照bean的id注入。
  3. Java的JDK提供本注解。

?

@Configuration注解

標記在類上
注解作用:作用等同于beans.xml配置文件,當前注解聲明的類中,編寫配置信息,所以我們把
@Configuration聲明的類稱之為配置類。

//通過配置xml的獲取
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
accountService = ac.getBean("accountService ");
//通過配置類,初始化Spring的ioc容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//獲取AccountService接口的實現類對象
accountService = ac.getBean(AccountService.class);

@Import注解

標記在類上
注解作用:導入其他配置類(對象)
相當于XML配置文件中的標簽

<import resource="classpath:applicationContext-dao.xml"/>

引用場景
在配置文件按配置項目時使用xml分層
例如 mvc.xml,dao.xml,service.xml分別配置提高可讀性和可維護性,使用 import 引入同一個xml中進行讀取。
多個configuration配置類時使用
@Import(配置類.class) 或 @Import({配置類.class,配置類.class}) 參數為數組加載多個配置類
?

@PropertySource注解

標記在類上
注解作用:引入外部屬性文件(db.properties)
相當于XML配置文件中的context:property-placeholder標簽

<context:property-placeholder location="classpath:jdbc.properties"/>
@Configuration 
@PropertySource({"db.properties"})
public class SpringConfigClass {}

或者

@PropertySource("classpath:db.properties")

@Value注解

標記在成員變量或set方法上
注解作用:給簡單類型變量賦值
相當于XML配置文件中的標簽

<property name="driverClass" value="${jdbc.driver}"/>

@Bean注解

標記在配置類中的方法上
注解作用:將方法的返回值存儲到Spring IOC容器中
相當于XML配置文件中的標簽

舉例 @PropertySource @Value @Bean 的整合

@Configuration 
@PropertySource({"db.properties"})
public class SpringConfigClass {     @Value("${jdbc.driver}")     private String dataSource;     @Value("${jdbc.url}")     private String url;     @Value("${jdbc.username}")     private String userName;     @Value("${jdbc.password}")     private String passWord;     @Bean     public DruidDataSource dataSource() {         DruidDataSource druidDataSource = new DruidDataSource();         druidDataSource.setDriverClassName(dataSource);         druidDataSource.setUrl(url);         druidDataSource.setUsername(userName);         druidDataSource.setPassword(passWord);         return druidDataSource;     } 
}

等價于 xml

<context:property-placeholder location="classpath*:db.properties"/>     
<!--注入 druid-->     
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">         <property name="driverClassName" value="${jdbc.driver}"></property>         <property name="url" value="${jdbc.url}"></property>         <property name="username" value="${jdbc.username}"></property>        <property name="password" value="${jdbc.password}"></property>     
</bean>

@ComponentScan(“com.*”)注解

標記在配置類上
相當于XML配置文件中的context:component-scan標簽

<context:component-scan base-package="com.spring.annotation" use-default-filters="false">   <context:include-filter type="custom"  expression="com.spring.annotation.filter.ColorBeanLoadFilter" />   <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Component" />
</context:component-scan>
@Configuration 
@ComponentScan 
public class SpringConfigClass { }

屬性
value:指定要掃描的package; 若value值為空則掃描當前配置類的包以及子包。
includeFilters=Filter[]:指定只包含的組件
excludeFilters=Filter[]:指定需要排除的組件;
useDefaultFilters=true/false:指定是否需要使用Spring默認的掃描規則:被@Component, @Repository, @Service, @Controller或者已經聲明過@Component自定義注解標記的組件;
在過濾規則Filter中:
FilterType:指定過濾規則,支持的過濾規則有
ANNOTATION:按照注解規則,過濾被指定注解標記的類;
ASSIGNABLE_TYPE:按照給定的類型;
ASPECTJ:按照ASPECTJ表達式;
REGEX:按照正則表達式
CUSTOM:自定義規則;
value:指定在該規則下過濾的表達式;

	掃描指定類文件    @ComponentScan(basePackageClasses = Person.class) 掃描指定包,使用默認掃描規則,即被@Component, @Repository, @Service, @Controller或者已經聲明過@Component自定義注解標記的組件;    	   @ComponentScan(value = "com.yibai") 掃描指定包,加載被@Component注解標記的組件和默認規則的掃描(因為useDefaultFilters默認為true@ComponentScan(value = "com", includeFilters = { @Filter(type = FilterType.ANNOTATION, value = Component.class) }) 掃描指定包,只加載Person類型的組件    @ComponentScan(value = "com", includeFilters = { @Filter(type = FilterType.ASSIGNABLE_TYPE, value = Person.class) }, useDefaultFilters = false) 掃描指定包,過濾掉被@Component標記的組件    @ComponentScan(value = "com", excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = Component.class) }) 掃描指定包,自定義過濾規則    @ComponentScan(value = "com.yibai", includeFilters = { @Filter(type = FilterType.CUSTOM, value = ColorBeanLoadFilter.class) }, useDefaultFilters = true

舉例

// useDefaultFilters = false 關閉默認過濾使用創建的過濾  
// value = {UserAllAnnonService.class, UserAllAnnonMapper.class} 只掃描這兩個接口的組件注解
@Configuration 
@ComponentScan(includeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = {UserAllAnnonService.class, UserAllAnnonMapper.class})},useDefaultFilters = false) 
public class SpringConfigClass { }

?

@EnableAspectJAutoProxy 開啟Aop注解支持

對應標簽
aop:aspectj-autoproxy/
舉例

@Configuration 
@ComponentScan 
@PropertySource("classpath:db.properties") 
@ImportResource({"classpath:beans.xml"}) 
@EnableAspectJAutoProxy 
public class SpringConfigClass {...}

@EnableTransactionManagement 開啟注解事務控制

對應xml標簽

<tx:annotation-driven/>
@Configuration 
@ComponentScan 
@PropertySource("classpath:sqlLink.properties") 
@ImportResource({"classpath:beans.xml"}) 
@EnableTransactionManagement 
public class SpringConfigClass {...}

@Transactional() 事務處理,加到方法上,開啟當前方法的事務支持

常用屬性
transactionManager 屬性: 設置事務管理器,如果不設置默認是transactionManager。
isolation屬性: 設置事務的隔離級別。
propagation屬性: 事務的傳播行為。

@Override 
@Transactional(transactionManager = "transactionManager", isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED) 
public Integer saveUser(User user) {    Integer integer = userMapper.saveUser(user);    return integer; 
}

?

其他注解

@Scope(“prototype”)

標記在類上,配合@Component使用
注解作用:指定對象的作用范圍:單例模式(singleton)還是多例模式(prototype)
?

@PostConstruct、@PreDestroy 生命周期注解

@PostConstruct ==> init-method
舉例:

@Component
public class School {@PostConstructpublic void init(){System.out.println("annotation PostConstruct");}
}
    <bean id = "school" class="com.abc.model.School" init-method="init"></bean>

@PreDestroy ==> destroy
舉例:?

@Component
public class School {@PreDestroypublic void destroyMethod(){System.out.println("annotation PostConstruct");}
}
    <bean id = "school" class="com.abc.model.School" destroy-method="init"></bean>

?

@ImportResource({“classpath:beans.xml”})

引入外部配置,此注解適用于配置類和xml配置共同存在
舉例

@Configuration 
@ComponentScan 
@PropertySource("classpath:db.properties") 
@ImportResource({"classpath:beans.xml"}) 
public class SpringConfigClass {...}

對應xml配置

<import resource="beans.xml"></import>

@Aspect 切面

注解作用:當前類的對象,是一個切面類

<aop:config><aop:aspect id="" ref="" /></aop:config>

@Pointcut 切點

@Pointcut("execution(public void com.itheima.service.AccountServiceImpl.save())") 
public void pointcut() {}

對應xml

<aop:pointcut id="pointcutService" expression="execution(* com.spring.service.UserServiceImpl.*(..))"/>

@After(“pointcut()”) 后置通知
@AfterThrowing(“pointcut()”) 異常通知
@AfterReturning(“pointcut()”) 最終通知
@Before(“pointcut()”) 前置通知
舉例

@Before("pointcut()") 
public void beforePrintLog() {     System.out.println("方法執行之前,輸出日志"); 
}

對應xml

<aop:before method="beforePrintLog" pointcut-ref="pointcutService"/>

@Around(“pointcut()”) 環繞通知

//要求必須要傳遞一個參數: ProceedingJoinPoint 
@Around("pointcut()") 
public void aroundPrint(ProceedingJoinPoint joinPoint) {}

@MapperScan

指定要變成實現類的接口所在的包,然后包下面的所有接口在編譯之后都會生成相應的實現類

@MapperScan("com")

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/273543.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/273543.shtml
英文地址,請注明出處:http://en.pswp.cn/news/273543.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

安卓模擬器bluestacks mac地址修改教程

http://szmars2008.blog.163.com/blog/static/118893702201373181349348/ 轉載于:https://www.cnblogs.com/prayer521/p/4069037.html

Docker 搭建 ELK 日志系統,并通過 Kibana 查看日志

Docker 搭建 ELK 日志系統,并通過 Kibana 查看日志 docker-compose.yml version: 3 services:elasticsearch:image: elasticsearch:7.7.0 #鏡像container_name: elasticsearch #定義容器名稱restart: always #開機啟動&#xff0c;失敗也會一直重啟environment:- "cl…

蟠桃記

Problem Description 喜歡西游記的同學肯定都知道悟空偷吃蟠桃的故事&#xff0c;你們一定都覺得這猴子太鬧騰了&#xff0c;其實你們是有所不知&#xff1a;悟空是在研究一個數學問題&#xff01; 什么問題&#xff1f;他研究的問題是蟠桃一共有多少個&#xff01; 不過&#…

Spring 定時任務動態管理

管理 Spring 中定時任務 pom.xml <properties><hutool.version>5.6.6</hutool.version><lombok.version>1.18.20</lombok.version><spring-boot.web.version>2.2.10.RELEASE</spring-boot.web.version> </properties><de…

高效率Oracle SQL語句

1、Where子句中的連接順序&#xff1a; ORACLE采用自下而上的順序解析WHERE子句。 根據這個原理&#xff0c;表之間的連接必須寫在其他WHERE條件之前&#xff0c; 那些可以過濾掉最大數量記錄的條件必須寫在WHERE子句的末尾。 舉例&#xff1a; (低效) select ... from table1…

RabbitMQ Management:Management API returned status code 500

錯誤顯示&#xff1a; 解決方案&#xff1a; 因為是使用docker 容器安裝的&#xff0c;所有需要進入容器 docker exec -it rabbitmq /bin/bash進入目錄 cd /etc/rabbitmq/conf.d/執行命令 echo management_agent.disable_metrics_collector false > management_agent.dis…

Android JNI和NDK學習(5)--JNI分析API

Java類型和本地類型對應 在如下情況下&#xff0c;需要在本地方法中應用java對象的引用&#xff0c;就會用到類型之間的轉換&#xff1a; java方法里面將參數傳入本地方法&#xff1b;在本地方法里面創建java對象&#xff1b;在本地方法里面return結果給java程序。Java基本類型…

RabbitMq 消費失敗,重試機制

方案一&#xff1a; 本地消息表 定時任務 本地消息表&#xff1a;主要用于存儲 業務數據、交換機、隊列、路由、次數 定時任務&#xff1a;定時掃描本地消息表&#xff0c;重新給業務隊列投遞消息。 具體思路&#xff1a;業務隊列消費失敗時&#xff0c;把 業務數據、交換機、…

Android常用的工具類

主要介紹總結的Android開發中常用的工具類&#xff0c;大部分同樣適用于Java。目前包括HttpUtils、DownloadManagerPro、ShellUtils、PackageUtils、 PreferencesUtils、JSONUtils、FileUtils、ResourceUtils、StringUtils、 ParcelUtils、RandomUtils、ArrayUtils、ImageUtils…

0. Spring 基礎

BeanDefinition BeanDefinition 表示 Bean 定義&#xff1a; Spring根據BeanDefinition來創建Bean對象&#xff1b;BeanDefinition有很多的屬性用來描述Bean&#xff1b;BeanDefiniton是Spring中非常核心的概念。BeanDefiniton中重要的屬性&#xff1a; a. beanClass&#xf…

1. Spring 源碼:Spring 解析XML 配置文件,獲得 Bena 的定義信息

通過 Debug 運行 XmlBeanDefinitionReaderTests 類的 withFreshInputStream() 的方法&#xff0c;調試 Spring 解析 XML 配置文件&#xff0c;獲得 Bean 的定義。 大體流程可根據序號查看&#xff0c;xml 配置文件隨便看一眼&#xff0c;不用過多在意。 <?xml version&qu…

c++ 讀取文件 最后一行讀取了兩次

用ifstream的eof()&#xff0c;竟然讀到文件最后了&#xff0c;判斷eof還為false。網上查找資料后&#xff0c;終于解決這個問題。 參照文件&#xff1a;http://tuhao.blogbus.com/logs/21306687.html 在使用C/C讀文件的時候&#xff0c;一定都使用過eof&#xff08;&#xff0…

java中的io系統詳解(轉)

Java 流在處理上分為字符流和字節流。字符流處理的單元為 2 個字節的 Unicode 字符&#xff0c;分別操作字符、字符數組或字符串&#xff0c;而字節流處理單元為 1 個字節&#xff0c;操作字節和字節數組。 Java 內用 Unicode 編碼存儲字符&#xff0c;字符流處理類負責將外部的…

js獲取字符串最后一個字符代碼

方法一&#xff1a;運用String對象下的charAt方法 charAt() 方法可返回指定位置的字符。 代碼如下 復制代碼 str.charAt(str.length – 1) 請注意&#xff0c;JavaScript 并沒有一種有別于字符串類型的字符數據類型&#xff0c;所以返回的字符是長度為 1 的字符串 方法二&#…

Unity3D Shader入門指南(二)

關于本系列 這是Unity3D Shader入門指南系列的第二篇&#xff0c;本系列面向的對象是新接觸Shader開發的Unity3D使用者&#xff0c;因為我本身自己也是Shader初學者&#xff0c;因此可能會存在錯誤或者疏漏&#xff0c;如果您在Shader開發上有所心得&#xff0c;很歡迎并懇請您…

JVM:如何分析線程堆棧

英文原文&#xff1a;JVM: How to analyze Thread Dump 在這篇文章里我將教會你如何分析JVM的線程堆棧以及如何從堆棧信息中找出問題的根因。在我看來線程堆棧分析技術是Java EE產品支持工程師所必須掌握的一門技術。在線程堆棧中存儲的信息&#xff0c;通常遠超出你的想象&…

一個工科研究生畢業后的職業規劃

http://blog.csdn.net/wojiushiwo987/article/details/8592359一個工科研究生畢業后的職業規劃 [wojiushiwo987個人感觸]:說的很誠懇&#xff0c;對于馬上面臨畢業的我很受用&#xff0c;很有啟發。有了好的職業生涯規劃&#xff0c;才有了前進的方向和動力&#xff0c;才能…

SQLSERVER中如何忽略索引提示

SQLSERVER中如何忽略索引提示 原文:SQLSERVER中如何忽略索引提示SQLSERVER中如何忽略索引提示 當我們想讓某條查詢語句利用某個索引的時候&#xff0c;我們一般會在查詢語句里加索引提示&#xff0c;就像這樣 SELECT id,name from TB with (index(IX_xttrace_bal)) where bal…

JavaScript——以簡單的方式理解閉包

閉包&#xff0c;在一開始接觸JavaScript的時候就聽說過。首先明確一點&#xff0c;它理解起來確實不復雜&#xff0c;而且它也非常好用。那我們去理解閉包之前&#xff0c;要有什么基礎呢&#xff1f;我個人認為最重要的便是作用域&#xff08;lexical scope&#xff09;&…

jquery實現二級聯動不與數據庫交互

<select id"pro" name"pro" style"width:90px;"></select> <select id"city" name"city" style"width: 90px"></select> $._cityInfo [{"n":"北京市","c"…