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


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

1. 標記在類上,也可以放在接口上
2. 注解作用:把AccountDao實現類對象交由Spring IOC容器管理
相當於XML配置文件中的Bean標簽

<bean id="userAnnonMapper" class="com.spring.mapper.UserAnnonMapperImpl"></bean>

3. 注解Value屬性:相當於bean標簽id,對象在IOC容器中的唯一標識,可以不寫,默認值是當前類
首字母縮寫的類名。注入時需要注意此名稱!!。
4. 三個衍射注解分別是:@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"/>

3. 按照變量的數據類型注入,它只能注入其他的bean類型
4. 注意事項:
成員變量的接口數據類型,有多個實現類的時候,要使用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"/>

3. name屬性:指定bean的id
4. 如果不寫name屬性則按照變量數據類型注入,數據類型是接口的時候注入其實現類。如果定義
name屬性,則按照bean的id注入。
5. 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.yibai", includeFilters = { @Filter(type = FilterType.ANNOTATION, value = Component.class) })
掃描指定包,只加載Person類型的組件
   @ComponentScan(value = "com.yibai", includeFilters = { @Filter(type = FilterType.ASSIGNABLE_TYPE, value = Person.class) }, useDefaultFilters = false)
掃描指定包,過濾掉被@Component標記的組件
   @ComponentScan(value = "com.yibai", excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = Component.class) })
掃描指定包,自定義過濾規則
   @ComponentScan(value = "com.yibai", includeFilters = { @Filter(type = FilterType.CUSTOM, value = ColorBeanLoadFilter.class) }, useDefaultFilters = true

舉例

@Configuration
@ComponentScan(
includeFilters
= {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = {UserAllAnnonService.class, UserAllAnnonMapper.class})},
useDefaultFilters = false) public class SpringConfigClass { }

解釋,

useDefaultFilters = false 關閉默認過濾使用創建的過濾  

value = {UserAllAnnonService.class, UserAllAnnonMapper.class} 只掃描這兩個接口的組件注解

 

@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 ==> init-method
@PreDestroy ==> destroy

@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("cn.zys.mapper")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM