前面创造的类都一样除了不要xml配置文件一样的就不写了:
这是代替xml的配置文件,用到了
@Configuration还有@ComponentScan(basePackages = {“cn.zsp”})
链接:https://blog.csdn.net/qq_42388853/article/details/108305350
package cn.zsp.spring5.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = {"cn.zsp"})
public class SpringConfig {
}
test2是我们的测试类,这里的new 变成了AnnotationConfigApplicationContext
package cn.zsp.spring5.testdemo;
import cn.zsp.spring5.config.SpringConfig;
import cn.zsp.spring5.service.UserService;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestDemo1 {
@Test
public void test1(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.show();
}
@Test
public void test2(){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
UserService userService = context.getBean("userService", UserService.class);
userService.show();
}
}