Article From:https://segmentfault.com/q/1010000011136497
Question:

This is the configuration in webxml

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value> 
        classpath:application-context.xml </param-value>
    </context-param>

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

    <servlet>
        <servlet-name>example</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>

How to get bean through controller? If you use ClassPathApplicationContext to get the wrong report, what can I do? Who can help your big brother

Answer 0:

Getting bean in controller can use annotations:
1.Add to your Spring configuration <context:component-scan base-package="cn.lonecloud.xxx" annotation-config="true"/>
2.For example, you need to get a Bean of userService
Use@Autowiredannotation

    @Autowired
    protected UserService userService;

3.The premise needs to be added to the annotation class you need@service

@Service
public class UserService

You can get it

Answer 1:

Write a springUtils class
Add this bean to the XML of spring
<bean class=”com.xxx.util.SpringUtils”/>

springUtilsInherit BeanFactoryPostProcessor classes
private static ConfigurableListableBeanFactory beanFactory; // SpringApplication context environment
Add this property (getter and setter do not write)
The following method is to get bean
public static <T> T getBean(String name) throws BeansException {

    return (T) beanFactory.getBean(name);
}

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *