Spring之Bean學習

簡述:Spring框架主要是涉及到IOC(控制反轉)AOP(切面編程)兩大重點java

IOC和DI(依賴注入)其實就是等同的意思,就是建立對象和維護對象,放在一個容器裏,直接依賴注入便可使用spring

AOP的存在目的是爲了解耦即高內聚,低耦合apache

Bean的取值範圍
    Singleton:一個Spring容器中只有一個Bean的實例,此爲Spring的默認配置,全容器共享一個實例
    Prototype:每次調用新建一個Bean的實例
    Request:Web項目中,給每個http request新建一個Bean實例
    Session:Web項目中,給每個http session新建一個Bean實例
    GlobalSession:這個只在portal應用中有用,給每個global http session新建一個Bean實例編程

Bean的初始化和銷燬
    一、java配置方式:使用@BeaninitMethoddestroyMethod(至關於xml配置的init-method和destory-      method)
    二、註解方式:利用JSR-250@PostConstruct@PreDestroy
    initMethod和destoryMethod指定BeanWayService類的init和destory方法在構造以後、Bean銷燬以前執行session

  代碼及運行結果以下:app

 

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;框架


@Configuration // 聲明當前是配置類
@ComponentScan("com.pkb.prepost") // 自動掃描該包下的全部service、component、repository、controller
public class PrePostConfig
{
    // 聲明bean實例
    @Bean(initMethod = "init", destroyMethod = "destory")
    BeanWayService beanWayService()
    {
        return new BeanWayService();
    }dom

    @Bean
    JSR250WayService jsr250WayService()
    {
        return new JSR250WayService();
    }
}函數


public class BeanWayService
{
    public void init()
    {
        System.out.println("@Bean-init-method");
    }post

    public BeanWayService()
    {
        super();
        System.out.println("初始化構造函數-BeanWayService");
    }

    public void destory()
    {

        System.out.println("@Bean-destory-method");
    }

}

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;


public class JSR250WayService
{
    @PostConstruct // 在構造函數執行以後執行
    public void init()
    {
        System.out.println("jsr250-init-method");
    }

    public JSR250WayService()
    {
        super();
        System.out.println("初始化構造函數-JSR250WayService");
    }

    @PreDestroy // 在Bean銷燬以前執行
    public void destroy()
    {
        System.out.println("jsr250-destroy-method");
    }
}


import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class Main
{

    public static void main(String[] args)
    {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
            PrePostConfig.class);
        BeanWayService service = context.getBean(BeanWayService.class);
        JSR250WayService service1 = context.getBean(JSR250WayService.class);
        context.close();
    }

}

spring事件BeanBean之間的消息通訊提供了支持
    一、自定義事件、繼承ApplicationEvent
    二、定義事件監聽器,實現ApplicationListener
    三、使用容器發佈事件

 代碼及運行結果以下:

import org.springframework.context.ApplicationEvent;


public class DemoEvent extends ApplicationEvent
{
    private String msg;

    public DemoEvent(Object source, String msg)
    {
        super(source);
        this.msg = msg;
    }

    public String getMsg()
    {
        return msg;
    }

    public void setMsg(String msg)
    {
        this.msg = msg;
    }

}

 

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;


// 實現ApplicationListener接口並制定監聽的事件類型
@Component
public class DemoListenter implements ApplicationListener<DemoEvent>
{

    // 使用onApplicationEvent方法對消息進行接受處理
    public void onApplicationEvent(DemoEvent event)
    {
        String msg = event.getMsg();
        System.out.println("我(bean-demoListener)接收到了bean-demoPublisher發佈的消息:" + msg);
    }

}

 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;


@Component
public class DemoPublisher
{

    @Autowired
    ApplicationContext applicationContext;// 注入applicationContext用來發布事件

    // 使用publish方法來發布
    public void publish(String msg)
    {
        applicationContext.publishEvent(new DemoEvent(this, msg));
    }

}

 

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


@Configuration
@ComponentScan("com.pkb.event")
public class EventConfig
{}

 

import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class Main
{

    public static void main(String[] args)
    {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
            EventConfig.class);

        DemoPublisher demoPublisher = context.getBean(DemoPublisher.class);
        demoPublisher.publish("hello application event");
        context.close();
    }

}

Spring Aware的目的是爲了讓Bean得到Spring容器的服務,由於ApplicationContext接口集成了
    MessageSource接口、ApplicationEventPublisher接口和ResourceLoader接口,因此Bean集成了
    ApplicationConextAware能夠得到Spring容器的全部服務

   代碼及運行結果以下:

   

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


@Configuration
@ComponentScan("com.pkb.aware")
public class AwareConfig
{}


import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;


// 實現BeanNameAware, ResourceLoaderAware接口,得到Bean名稱和資源加載的全部服務
@Service
public class AwareService implements BeanNameAware, ResourceLoaderAware
{

    private String beanName;

    private ResourceLoader loader;

    // 需重寫setResourceLoader方法
    public void setResourceLoader(ResourceLoader resourceLoader)
    {

        this.loader = resourceLoader;
    }

    // 需重寫setBeanName方法
    public void setBeanName(String beanName)
    {
        this.beanName = beanName;

    }

    public void outputResult()
    {
        System.out.println("Bean的名稱爲: " + beanName);
        Resource resource = loader.getResource("classpath:com/pkb/aware/test.txt");
        try
        {
            System.out.println(
                "ResourceLoader加載文件的內容爲: " + IOUtils.toString(resource.getInputStream()));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public ResourceLoader getLoader()
    {
        return loader;
    }

    public void setLoader(ResourceLoader loader)
    {
        this.loader = loader;
    }

    public String getBeanName()
    {
        return beanName;
    }

}

import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class Main
{

    public static void main(String[] args)
    {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
            AwareConfig.class);

        AwareService awareService = context.getBean(AwareService.class);
        awareService.outputResult();
        context.close();
    }

}

//在com.pkb.aware包下建立test.txt文件並任意寫入內容

spring EL表達方式
    一、注入普通字符
    二、注入操做系統屬性
    三、注入表達式運算結果
    四、注入其餘Bean的屬性
    五、注入文件內容
    六、注入網址內容
    七、注入屬性文件

代碼及結果以下:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


@Service
public class DemoService
{
    @Value("其餘類的屬性") // 注入普通字符串
    private String another;

    public String getAnother()
    {
        return another;
    }

    public void setAnother(String another)
    {
        this.another = another;
    }

}

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;


@Configuration
@ComponentScan("com.pkb.el")
@PropertySource("classpath:com/pkb/el/test.properties")
public class ElConfig
{
    @Value("I Love You!") // 注入普通字符
    private String normal;

    @Value("#{systemProperties['os.name']}") // 注入操做系統
    private String osName;

    // 注入表達式結果
    @Value("#{T(java.lang.Math).random()*100.0}")
    private double randomNumber;

    // 注入其餘Bean屬性
    @Value("#{demoService.another}")
    private String fromAnother;

    // 注入文件資源
    @Value("classpath:com/pkb/el/test.txt")
    private Resource testFile;

    // 注入網址資源
    @Value("http://www.baidu.com")
    private Resource testUrl;

    // 注入配置文件
    @Value("${book.name}")
    private String bookName;

    @Autowired
    private Environment environment;

    @Bean
    public static PropertySourcesPlaceholderConfigurer configurer()
    {
        return new PropertySourcesPlaceholderConfigurer();
    }

    public void outputResource()
    {
        try
        {
            System.out.println(normal);
            System.out.println(osName);
            System.out.println(randomNumber);
            System.out.println(fromAnother);
            System.out.println(IOUtils.toString(testFile.getInputStream()));
            System.out.println(IOUtils.toString(testUrl.getInputStream()));
            System.out.println(bookName);
            System.out.println(environment.getProperty("book.author"));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

}

import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class Main
{

    public static void main(String[] args)
    {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
            ElConfig.class);
        ElConfig service = context.getBean(ElConfig.class);
        service.outputResource();
        context.close();
    }

}

//在com.pkb.el包下建立test.properties (book.author = zhangsan
//book.name = spring boot)和 test.txt (內容任意)

Spring支持AspectJ的註解切面編程
    一、使用@Aspect聲明是一個切面
    二、使用@After、@Before、@Around定義建言(advice),可直接將攔截規則(切點)做爲參數
    三、其中@After、@Before、@Around參數的攔截規則爲切點(PointCut),爲了使切點複用,
    可以使用@PointCut專門定義攔截規則,而後在@After、@Before、@Around參數中調用
    四、其中符合條件的每個被攔截處爲鏈接點(JoinPoint

 代碼及運行結果以下: 

//註解自己沒有功能,和xml同樣都是一種元數據即解釋數據的數據
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Action {
    String name();
}

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;


@Configuration // 聲明當前類爲配置類
@ComponentScan("com.pkb.aop")
@EnableAspectJAutoProxy // 開啓spring對AspectJ代理的支持
public class AopConfig
{

}

import org.springframework.stereotype.Service;


@Service
public class DemoAnnotationService
{
    @Action(name = "add")
    public void add()
    {
        System.out.println("該方法已被攔截...");
    }
}

import org.springframework.stereotype.Service;


@Service
public class DemoMethodService
{
    public void add()
    {
        System.out.println("編寫使用方法規則被攔截類...");
    }
}

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;


@Aspect // 聲明一個切面
@Component // 讓此切面成爲spring容器管理的bean
public class LogAspect
{
    // 聲明切點
    @Pointcut("@annotation(com.pkb.aop.Action)")
    public void annotationPointCut()
    {
        System.out.println("pointcut方法被調用...");
    }

    @After("execution(* com.pkb.aop.DemoAnnotationService.*(..))")
    public void after(JoinPoint joinPoint)
    {
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        Action action = method.getAnnotation(Action.class);
        System.out.println("註解式攔截 " + action.name());
    }

    @Before("execution(* com.pkb.aop.DemoMethodService.*(..))")
    public void before(JoinPoint joinPoint)
    {
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        System.out.println("方法規則式攔截 " + method.getName());
    }

}

import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class Main
{

    public static void main(String[] args)
    {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
            AopConfig.class);
        DemoAnnotationService service = context.getBean(DemoAnnotationService.class);
        DemoMethodService service1 = context.getBean(DemoMethodService.class);
        service.add();
        service1.add();
        context.close();
    }

}

相關文章
相關標籤/搜索