文章

Spring 常见代码汇总

一、控制台打印服务端地址

    public static void main(String[] args) throws UnknownHostException {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
        ConfigurableEnvironment environment = context.getEnvironment();
        String port = Optional.ofNullable(environment.getProperty("server.port")).orElse("8080");
        String contextPath = Optional.ofNullable(environment.getProperty("servlet.context-path")).orElse("/");
        log.info("Server Start Success , Link To Open : http://127.0.0.1:{}{}", port, contextPath);
    }

二、logback打印pattern日志到websocket中

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.ConsoleAppender;

public class WebSocketAppender extends ConsoleAppender<ILoggingEvent> {

    @Override
    protected void append(ILoggingEvent eventObject) {
        //输出到websocket
        getEncoder().encode(eventObject)
    }

}
 <!--    控制台日志   -->
    <property name="console_pattern"
              value="%date{yyyy-MM-dd HH:mm:ss} [%X{traceId}] [%X{nextId}] | %-5level | %thread | %logger | %msg%n   "/>


 
<appender name="WEBSOCKET_APPENDER" class="com.boommanpro.aobidao.game.log.WebSocketAppender">
        <encoder>
            <pattern>${console_pattern}</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>

三、BeanDefinitionRegistry通过读取配置注册Bean对象

        // 注册DependencyA
        BeanDefinition dependencyADefinition = BeanDefinitionBuilder.genericBeanDefinition(DependencyA.class).getBeanDefinition();
        registry.registerBeanDefinition("dependencyA", dependencyADefinition);

        // 注册DependencyB
        BeanDefinition dependencyBDefinition = BeanDefinitionBuilder.genericBeanDefinition(DependencyB.class).getBeanDefinition();
        registry.registerBeanDefinition("dependencyB", dependencyBDefinition);

        // 注册MainBean并设置构造函数依赖
        BeanDefinition mainBeanDefinition = BeanDefinitionBuilder.genericBeanDefinition(MainBean.class)
                .addConstructorArgReference("dependencyA")
                .addConstructorArgReference("dependencyB")
                .getBeanDefinition();
        registry.registerBeanDefinition("mainBean", mainBeanDefinition);