Home > Java > javaTutorial > body text

How to inject Bean using ApplicationContext in java

王林
Release: 2023-05-03 16:58:15
forward
1364 people have browsed it

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);
    }
Copy after login

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())
    }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!