About getting Spring, Bean

Asked 2 years ago, Updated 2 years ago, 51 views

Learning Spring.
I changed the sample code of the book a little, but
NullPointerException.

public classProductSampleRun{

    @Autowired
    private ProductService productService;

    public static void main(String args[]){
        ProductSampleRun productSampleRun=new ProductSampleRun();
        productSampleRun.execute();
    }

    public void execute() {

        // BeanFactory ctx = new ClassPathXmlApplicationContext(
        //      "/spring/application-config.xml";
        // ProductService productService=ctx.getBean(ProductService.class);

        productService.addProduct(newProduct(" stapler",100));

        Product product=productService.findByProductName(" stapler");
        System.out.println(product);
    }
}

As an accompanying information
ProductServiceImple is registered as @Component.
The web.xml contains ContextConfigLocation and ContextLoaderListener.
Component-Scan is written in the application-config.

I don't know Spring at all yet, but if you want to get Bean,
Do I have to do getBean without fail?(Comment section)
I thought I could use @Autowired...

java spring

2022-09-30 16:08

1 Answers

If it's a web project with SpringMVC, you should be able to go with @Autowired or @Resource.

public static void main(String args[]){
    ProductSampleRun productSampleRun=new ProductSampleRun();
    productSampleRun.execute();
}

The ProductSampleRun object was not managed by Spring, so Autowired did not work.

String[]xmlCfg = new String[] { "classpath:/spring/applicationContext-service.xml",
            "classpath:/spring/applicationContext-util.xml",
            "classpath:/spring/applicationContext.xml" }; 
ApplicationContext context=newFileSystemXmlApplicationContext(xmlCfg);
// 取 InspectionUtil bean
ProductSampleRun productSample=(ProductSampleRun) context.getBean(ProductSampleRun.class);

Try retrieving Bean using ApplicationContext as shown in .


2022-09-30 16:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.