Common classes in SpringMVC call Service interface

In SpringMVC, Controller can directly use the annotation @Resource to call the Service business logic layer, but how to operate when ordinary classes or tool classes want to call the Service interface?

Next provide two solutions

 

1. Reload the Spring configuration file to instantiate the context bean

ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext-common.xml");  
StudentService studentService = (StudentService)appContext.getBean("studentService");  

Use ClassPathXmlApplicationContext as the entry point to load the Spring configuration file under CLASSPATH, complete the loading of all Bean instances, and obtain Bean instances.

 

2. Implement ApplicationContextAware interface (recommended)

Through the ApplicationContextAware interface, the instantiated Bean can be obtained from the existing Spring context.

(1) Create the tool class SpringContextUtil to implement the ApplicationContextAware interface

@Component
public class SpringContextUtil implements ApplicationContextAware {
	
    private static ApplicationContext appCtx;
	
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        appCtx = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return appCtx;
    }
    
    // 添加getBean()方法,凭id获取容器管理的Bean
    public static Object getBean(String beanName) {
        return appCtx.getBean(beanName);
    }
	
}

(2) Inject the tool class SpringContextUtil into the Spring container

<bean id="springContextUtil" class="com.cn.unit.spring.SpringContextUtil"/>

(3) Configure the Listener that loads the Spring container in the project web.xml

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

(4) Then you can happily get the Bean in the Spring container

UserServiceImpl userService = (UserServiceImpl) SpringContextUtil.getBean("userService");
userService.insertUser(user);

 

 Give someone a rose hand to leave a fragrance, if it helps you, come 点个赞!

Guess you like

Origin blog.csdn.net/ii950606/article/details/100081293