1. 程式人生 > >1、Spring註解開發,第一天

1、Spring註解開發,第一天

第一天:Spring annotation開發

目錄:1、@Configuration與@Bean給容器註冊元件 2、@ConponentScan自動掃描註解

一、@Configuration與@Bean給容器註冊元件

1、舊版本中建立配置檔案和Bean

//實體類

package com.lee.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data//生成GET SET方法
@NoArgsConstructor//無參建構函式
@AllArgsConstructor//有參建構函式
public class Person {

    private Integer id;

    private String username;

    private String gender;

}

配置檔案

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="person" class="com.lee.bean.Person">
        <property name="id" value="1"></property>
        <property name="username" value="lee"></property>
        <property name="gender" value="male"></property>
    </bean>

</beans>

測試

package com.lee;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainTest {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Object person = context.getBean("person");
        System.out.println(person);
    }
}

結果:

Person(id=1, username=lee, gender=male)

2、Annotation中的配置檔案和Bean

配置類

package com.lee.config;

import com.lee.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration//告訴Spring這是一個配置類
public class MainConfig {

    //Bean 給容器註冊一個bean,型別為返回值的型別,id預設使用方法名作為id
    //@Bean("名字")可以給bean修改名稱
    @Bean
    public Person person(){
        return new Person(2,"lee2","male2");
    }
}

測試類

package com.lee;

import com.lee.bean.Person;
import com.lee.config.MainConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainTest {

    public static void main(String[] args) {
//        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
//        Object person = context.getBean("person");
//        System.out.println(person);

        ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
        Person bean = context.getBean(Person.class);
        System.out.println(bean);
    }
}

測試結果:

Person(id=2, username=lee2, gender=male2)

總結

@Configuration等同於以前的配置檔案---告訴spring這是一個配置類

@Bean 給容器註冊一個bean,型別為返回值的型別,id預設使用方法名作為id

二、@ConponentScan自動掃描註解

1、原來xml

<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

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

</beans>

2、Annotation中的自動掃描

準備類

package com.lee.controller;

import org.springframework.stereotype.Controller;

@Controller
public class BookController {

}
package com.lee.service;

import org.springframework.stereotype.Service;

@Service
public class BookService {

}
package com.lee.dao;

import org.springframework.stereotype.Repository;

@Repository
public class BookDao {

}

配置檔案自動掃描

package com.lee.config;

import com.lee.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan("com.lee")//自動掃描 value指定要掃描的包
@Configuration//告訴Spring這是一個配置類
public class MainConfig {

    //Bean 給容器註冊一個bean,型別為返回值的型別,id預設使用方法名作為id
    //@Bean("名字")可以給bean修改名稱
    @Bean
    public Person person(){
        return new Person(2,"lee2","male2");
    }


}

測試類

package com.lee;

import com.lee.bean.Person;
import com.lee.config.MainConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainTest {

    public static void main(String[] args) {

        ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
        String[] names = context.getBeanDefinitionNames();
        for(String name : names){
            System.out.println(name);
        }
    }
}

測試結果

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
mainConfig
bookController
bookDao
bookService
person

3、@ComponentScan過濾功能

原始碼,component中有includeFilters和excludeFilters功能,能夠過濾要篩選的包

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.context.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.core.annotation.AliasFor;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan {
    
    @AliasFor("basePackages")
    String[] value() default {};

    boolean useDefaultFilters() default true;

    ComponentScan.Filter[] includeFilters() default {};

    ComponentScan.Filter[] excludeFilters() default {};

    @Retention(RetentionPolicy.RUNTIME)
    @Target({})
    public @interface Filter {
        FilterType type() default FilterType.ANNOTATION;

        @AliasFor("classes")
        Class<?>[] value() default {};

        @AliasFor("value")
        Class<?>[] classes() default {};

        String[] pattern() default {};
    }
}

配置類1

package com.lee.config;

import com.lee.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;

//@ComponentScan("com.lee")//自動掃描 value指定要掃描的包
@Configuration//告訴Spring這是一個配置類
@ComponentScan(value="com.lee",excludeFilters = {
        @ComponentScan.Filter(type=FilterType.ANNOTATION,value = Controller.class)
})
public class MainConfig {

    //Bean 給容器註冊一個bean,型別為返回值的型別,id預設使用方法名作為id
    //@Bean("名字")可以給bean修改名稱
    @Bean
    public Person person(){
        return new Person(2,"lee2","male2");
    }


}

測試1

mainConfig
bookDao
bookService
person

配置類2

package com.lee.config;

import com.lee.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;

//@ComponentScan("com.lee")//自動掃描 value指定要掃描的包
@Configuration//告訴Spring這是一個配置類
//@ComponentScan(value="com.lee",excludeFilters = {
//        @ComponentScan.Filter(type=FilterType.ANNOTATION,value = Controller.class)
//})
//includeFilters必須和useDefaultFilters=false一起使用才能起到作用
//useDefaultFilters預設是true,即預設掃描全部的包
@ComponentScan(value = "com.lee",useDefaultFilters=false,includeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)
})
public class MainConfig {

    //Bean 給容器註冊一個bean,型別為返回值的型別,id預設使用方法名作為id
    //@Bean("名字")可以給bean修改名稱
    @Bean
    public Person person(){
        return new Person(2,"lee2","male2");
    }


}

測試2

mainConfig
bookContro