SpringBoot使用ApplicationContext对象获取Bean

ApplicationContext对象是Spring容器的上下文对象。下面将介绍基于SpringBoot平台完成ApplicationContext对象的获取,并通过实例获取Spring管理的Bean。

(1)创建User(用户信息实体类),并在类上添加@Component注解。

import org.springframework.stereotype.Component;

/**
 * 用户信息实体类
 * @author pan_junbiao
 **/
@Component
public class User
{

}

(2)通过ApplicationContext对象获取Bean。

/**
 * SpringBoot获取ApplicationContext上下文对象
 * @author pan_junbiao
 **/
@SpringBootTest
@RunWith(SpringRunner.class)
public class IoCTest
{
    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void testIoc()
    {
        User user = (User)applicationContext.getBean("user");
        System.out.println(user);
    }
}

 

你可能感兴趣的:(Spring,Boot,我の原创,spring,boot)