关于WebApplicationInitializer的使用

关于WebApplicationInitializer的使用

首先在pom导入依赖

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>

编辑配置文件

package com.liang.config;

import com.liang.util.YamlPropertySourceFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;


@PropertySource(value = "classpath:application.yml", factory = YamlPropertySourceFactory.class)
@ComponentScan("com.liang")//扫描注册的进spring容器
@Configuration
public class SpringConfig {
}

然后编写初始化类实现WebApplicationInitializer

package com.liang;

import com.liang.config.SpringConfig;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;


public class WebApplicationStart implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.setServletContext(servletContext);
        applicationContext.register(SpringConfig.class);
        applicationContext.refresh();
        System.out.println("Hello World");
        String[] names = applicationContext.getBeanDefinitionNames();
        for (String name:names
             ) {
            System.out.println(name);
        }
        DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext);
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", dispatcherServlet);
        dispatcher.addMapping("/");

    }
}

读取yml文件的工具类

package com.liang.util;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Objects;
import java.util.Properties;

/**
 * 利用Spring自定义的ymal配置读取器
 */
public class YamlPropertySourceFactory implements PropertySourceFactory {

    /**
     * Create a {@link PropertySource} that wraps the given resource.
     *
     * @param name     the name of the property source
     *                 (can be {@code null} in which case the factory implementation
     *                 will have to generate a name based on the given resource)
     * @param resource the resource (potentially encoded) to wrap
     * @return the new {@link PropertySource} (never {@code null})
     * @throws IOException if resource resolution failed
     * @See 解析器 org.springframework.context.annotation.ConfigurationClassParser
     */
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        // 请配置注解参数:ignoreResourceNotFound = true
        try {
            String filename = Objects.requireNonNull(resource.getResource().getFilename());
            //1.创建yaml文件解析工厂
            YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
            //2.设置资源内容
            yaml.setResources(resource.getResource());
            //3.解析成properties文件
            Properties properties = yaml.getObject();
            if (properties == null) {
                throw new FileNotFoundException();
            }
            //4.返回符合spring的PropertySource对象
            return name != null ? new PropertiesPropertySource(name, properties)
                    : new PropertiesPropertySource(filename, properties);
        } catch (Exception e) {
            e.printStackTrace();
            throw new IOException("Yaml解析异常,异常原因:" + e.getMessage());
        }

    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爪哇进阶者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值