Spring使用指南 ~ 4ApplicationContext 配置详解

Posted 戴泽supp

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring使用指南 ~ 4ApplicationContext 配置详解相关的知识,希望对你有一定的参考价值。

ApplicationContext 配置详解

一、应用程序事件

package com.luo.spring.guides.event.xml;

import org.springframework.context.ApplicationEvent;

public class MessageEvent extends ApplicationEvent 
    private final String msg;

    public MessageEvent(Object source, String msg) 
        super(source);
        this.msg = msg;
    

    public String getMessage() 
        return msg;
    

1、xml 形式

package com.luo.spring.guides.event.xml;

import org.springframework.context.ApplicationListener;

public class MessageEventListener implements ApplicationListener<MessageEvent> 
    @Override
    public void onApplicationEvent(MessageEvent event) 
        MessageEvent msgEvt = event;
        System.out.println("Received: " + msgEvt.getMessage());
    

package com.luo.spring.guides.event.xml;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class Publisher implements ApplicationContextAware 
    private ApplicationContext ctx;

    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException 
        this.ctx = applicationContext;
    

    public void publish(String message) 
        ctx.publishEvent(new MessageEvent(this, message));
    



<?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="publisher" class="com.luo.spring.guides.event.xml.Publisher"/>

    <bean id="messageEventListener" 
        class="com.luo.spring.guides.event.xml.MessageEventListener"/>
</beans>

测试

package com.luo.spring.guides.event.xml;

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

/**
 * @author : archer
 * @date : Created in 2022/12/9 11:29
 * @description :
 */
public class Main 

    public static void main(String... args) 
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "classpath:event/app-context-xml.xml");

        Publisher pub = (Publisher) ctx.getBean("publisher");
        pub.publish("I send an SOS to the world... ");
        pub.publish("... I hope that someone gets my...");
        pub.publish("... Message in a bottle");
    

输出

Received: I send an SOS to the world…
Received: … I hope that someone gets my…
Received: … Message in a bottle

2、注解形式

package com.luo.spring.guides.event.domain;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class Publisher implements ApplicationContextAware 
    private ApplicationContext ctx;

    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException 
        this.ctx = applicationContext;
    

    public void publish(String message) 
        ctx.publishEvent(new MessageEvent(this, message));
    

package com.luo.spring.guides.event.annotation;

import com.luo.spring.guides.event.domain.MessageEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * @author : archer
 * @date : Created in 2022/12/9 11:35
 * @description :
 */
@Component
public class MessageEventListener 

    @EventListener(classes = MessageEvent.class)
    public void messageEventListener(MessageEvent messageEvent)
        System.out.println("Received: " + messageEvent.getMessage());
    


测试

package com.luo.spring.guides.event.annotation;

import com.luo.spring.guides.event.domain.Publisher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author : archer
 * @date : Created in 2022/12/9 11:29
 * @description :
 */
public class Main 

    public static void main(String... args) 
        ApplicationContext ctx = new AnnotationConfigApplicationContext(
                "com.luo.spring.guides.event");

        Publisher pub = (Publisher) ctx.getBean("publisher");
        pub.publish("I send an SOS to the world... ");
        pub.publish("... I hope that someone gets my...");
        pub.publish("... Message in a bottle");
    

输出

Received: I send an SOS to the world…
Received: … I hope that someone gets my…
Received: … Message in a bottle

二、访问资源

test.txt

Dreaming with a Broken Heart

测试

package com.luo.spring.guides.resource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileUrlResource;
import org.springframework.core.io.Resource;

import java.io.File;

public class Main 
    public static void main(String... args) throws Exception 
        ApplicationContext ctx = new ClassPathXmlApplicationContext();

        File file = File.createTempFile("test", "txt");
        file.deleteOnExit();

        Resource res1 = ctx.getResource("file://" + file.getPath());
        displayInfo(res1);

        Resource res2 = ctx.getResource("classpath:test.txt");
        displayInfo(res2);

        Resource res3 = ctx.getResource("http://www.google.com");
        displayInfo(res3);
    

    private static void displayInfo(Resource res) throws Exception 
        System.out.println(res.getClass());
        if (!(res instanceof FileUrlResource)) 
            System.out.println(res.getURL().getContent());//FileUrlResource不能使用getURL().getContent()
        
        System.out.println("");
    


输出

class org.springframework.core.io.FileUrlResource

class org.springframework.core.io.ClassPathResource
sun.net.www.content.text.PlainTextInputStream@12405818

class org.springframework.core.io.UrlResource
sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@400cff1a

三、profiles

  • 通过 -Dspring.profiles.active=highschool 指定要使用的配置文件(highschool 是 profile 中的值)
package com.luo.spring.guides.profiles.impl;

public class Food 
    private String name;

    public Food() 
    

    public Food(String name) 
        this.name = name;
    

    public String getName() 
        return name;
    

    public void setName(String name) 
        this.name = name;
    

package com.luo.spring.guides.profiles.impl;

import java.util.List;

public interface FoodProviderService 
    List<Food> provideLunchSet();

package com.luo.spring.guides.profiles.impl.kindergarten;

import com.luo.spring.guides.profiles.impl.Food;
import com.luo.spring.guides.profiles.impl.FoodProviderService;

import java.util.ArrayList;
import java.util.List;

public class KindergartenFoodProviderServiceImpl implements FoodProviderService 
    @Override
    public List<Food> provideLunchSet() 
        List<Food> lunchSet = new ArrayList<>();
        lunchSet.add(new Food("Milk"));
        lunchSet.add(new Food("Biscuits"));

        return lunchSet;
    

package com.luo.spring.guides.profiles.impl.highschool;

import com.luo.spring.guides.profiles.impl.Food;
import com.luo.spring.guides.profiles.impl.FoodProviderService;

import java.util.ArrayList;
import java.util.List;

public class HighSchoolFoodProviderServiceImpl implements FoodProviderService 
    @Override
    public List<Food> provideLunchSet() 
        List<Food> lunchSet = new ArrayList<>();
        lunchSet.add(new Food("Coke"));
        lunchSet.add(new Food("Hamburger"));
        lunchSet.add(new Food("French Fries"));

        return lunchSet;
    

1、xml 形式

highschool-config.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd"
        profile="highschool">

    <bean id="foodProviderService"
      class="com.luo.spring.guides.profiles.impl.highschool.HighSchoolFoodProviderServiceImpl"/>
</beans>

kindergarten-config.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd"
        profile="kindergarten">

    <bean id="foodProviderService" 
      class="com.luo.spring.guides.profiles.impl.kindergarten.KindergartenFoodProviderServiceImpl"/>
</beans>

测试

  • 启动类指定 -Dspring.profiles.active=highschool
package com.luo.spring.guides.profiles.xml;

import com.luo.spring.guides.profiles.impl.Food;
import com.luo.spring.guides.profiles.impl.FoodProviderService;
import org.springframework.context.support.GenericXmlApplicationContext;

import java.util.List;

//通过 -Dspring.profiles.active=highschool 指定要使用的配置文件
public class Main 
    public static void main(String... args) 
        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
        ctx.load("classpath:profiles/*-config.xml");
        ctx.refresh();

        FoodProviderService foodProviderService =
            ctx.getBean("foodProviderService", FoodProviderService.class);

        List<Food> lunchSet = foodProviderService.provideLunchSet();

        for (Food food: lunchSet) 
            System.out.println("Food: " + food.getName());
        

        ctx.close();
    

输出

Food: Coke
Food: Hamburger
Food: French Fries

2、注解形式

package com.luo.spring.guides.profiles.annotation;


import com.luo.spring.guides.profiles.impl.FoodProviderService;
import com.luo.spring.guides.profiles.impl.highschool.HighSchoolFoodProviderServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

/**
 * Created by iuliana.cosmina on 3/18/17.
 */
@Configuration
@Profile("highschool")
public class HighschoolConfig 

	@Bean
	public FoodProviderService foodProviderService()
		return new HighSchoolFoodProviderServiceImpl();
	

package com.luo.spring.guides注销 MVC4 应用程序

新 Node Tools Express App 项目中的 Intellisense 错误

如何正确地将 Polyfills 添加到 SystemJS Angular 4 应用程序

在 MVC 4 应用程序中正确处理 HttpAntiForgeryException 的方法

如何为 Java 1.4 应用程序收集分析信息?

EF 5启用 - 迁移:在程序集中未找到上下文类型