可以使用AnnotationConfigApplicationContext类来加载不指定配置文件的Spring配置。这种方法使用了注解来配置Spring的bean。
以下是一个示例代码:
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainApp {
public static void main(String[] args) {
// 创建ApplicationContext对象,不指定配置文件
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
// 注册配置类
context.register(AppConfig.class);
// 刷新ApplicationContext
context.refresh();
// 获取bean
HelloWorld helloWorld = context.getBean(HelloWorld.class);
helloWorld.setMessage("Hello World!");
helloWorld.getMessage();
// 关闭ApplicationContext
context.close();
}
}
在上面的示例代码中,我们使用AnnotationConfigApplicationContext类创建了一个不指定配置文件的ApplicationContext对象。然后,我们使用register()方法注册了一个配置类(AppConfig),该配置类使用了@Configuration注解来指定了Spring的bean。接下来,我们调用refresh()方法刷新ApplicationContext,这将触发Spring框架根据配置类创建bean并将其加入到容器中。最后,我们使用getBean()方法获取bean,并调用它的方法。
需要注意的是,通过这种方式加载的Spring配置文件是基于注解的,因此需要在配置类中使用相应的注解来配置Spring的bean。