Home >Java >javaTutorial >How to inject Bean using ApplicationContext in java

How to inject Bean using ApplicationContext in java

王林
王林forward
2023-05-03 16:58:151443browse

Use ApplicationContext to inject Bean

It is springanother core interface or container after BeanFactory, allowing the container to create and obtain through the application context , management beans. Provides a central interface for configuration to applications. This is read-only while the application is running, but can be reloaded if the implementation supports this.

The first step: modify the project startup class and obtain the ApplicationContext

@SpringBootApplication
public class TestgroovyApplication {

    //获取应用程序上下文环境
    private static ApplicationContext applicationContext;

    public static void main(String[] args) {
        applicationContext = SpringApplication.run(TestgroovyApplication.class, args);
    }

The second step: modify the .groovy file created in the resources directory

/**
     * .
     * Groovy获取Bean
     */
    @Override
    void run() {
        log.info("Groovy开始执行,当前类{}", this.getClass())
        ScriptService service = TestgroovyApplication.applicationContext.getBean(ScriptService.class)
        log.info("ApplicationContext获取对象[{}]", service.class)
        List<Script> item = service.findAll()//执行bean中数据查询方法
        for (Script s : item) {
            log.info("创建人:[{}],规则id:[{}],名称:[{}]", s.getCreatePerson(), s.getRuleId(), s.getScriptName())
        }
        log.info("Groovy结束执行,当前类{}", this.getClass())
    }

Script running result:

How to inject Bean using ApplicationContext in java

The above is the detailed content of How to inject Bean using ApplicationContext in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete