gpt4 book ai didi

java - 是否有替换 ClassPathXmlApplicationContext.getBean 的 Spring 注解?

转载 作者:搜寻专家 更新时间:2023-11-01 00:55:09 24 4
gpt4 key购买 nike

我在一个 jar 中定义了一个类 MyFrontService,下面是我想如何使用它:

import blabla.MyFrontService;

public class Main {
public static void main(String[] args) {
MyFrontService.doThis();
}
}

FrontService 用作访问其他服务的入口点。这是它目前的定义方式(并且有效)。

MyFrontService.java:

public class MyFrontService {

public static void doThis(){

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("META-INF/springBeans.xml");
MyService1 myService1 = (MyService1) context.getBean("myService1");
myService1.doSomething();
context.close();

}
}

我的服务1.java:

package blabla.service;

@Service("myService1")
public class MyService1 {

public void doSomething(){
// some code
}
}

src/main/resources/META-INF/springBeans.xml:

(...)
<context:annotation-config />
<context:component-scan base-package="blabla.service" />
(...)

我想用这样的东西替换 MyFrontService.java 的代码:

@MagicAnnotation("what_path?/springBeans.xml")
public class MyFrontService {

@Autowired
private static MyService1 myService1;

public static void doThis(){
myService1.doSomething();
}
}

我已经从本网站和其他网站上的其他问题中阅读了很多内容。有时会说不可能,有时会使用@Configuration、@Import 等注释,但我无法使它们起作用。例如,使用

@ImportResource("classpath:META-INF/springBeans.xml")

调用 myService1.doSomething() 时触发 NullPointerException。

如果可以的话,我应该使用什么注解和什么路径?

最佳答案

使用Spring Boot框架,你将能够像这样写 smth

@Controller
@EnableAutoConfiguration
public class SampleController {

@RequestMapping("/")
@ResponseBody
String home() {
return "Hello World!";
}

public static void main(String[] args) throws Exception {
SpringApplication.run(SampleController.class, args);
}
}

关于java - 是否有替换 ClassPathXmlApplicationContext.getBean 的 Spring 注解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36459125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com