Spring不使用注解将对象放入Spring容器

import com.caiwei.config.Qwe; import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;

@Controller public class test {

@Autowired
DefaultListableBeanFactory defaultListableBeanFactory;

@Bean
public void qweqwe(){
    //指定作用域方式
    AnnotatedGenericBeanDefinition abd1 = new AnnotatedGenericBeanDefinition(Qwe.class);
    abd1.setScope("prototype");
    BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd1, "qwe");
    defaultListableBeanFactory.registerBeanDefinition("qwe",definitionHolder.getBeanDefinition());
    //不指定作用域方式

// AnnotatedBeanDefinitionReader abd = new AnnotatedBeanDefinitionReader(defaultListableBeanFactory); // abd.registerBean(Qwe.class); }

@RequestMapping("/test")
public String test(){
    Qwe qwe = (Qwe) defaultListableBeanFactory.getBean("qwe");
    //单例模式第一次请求Q2q为空,原型模式每次请求Q2q都为空
    qwe.setQ2q(123);
    return "test";
}

}

经验分享 程序员 微信小程序 职场和发展