1.去除xml配置文件
之前需要在xml文件中配置需要扫描的包,也可以通过注解实现。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="com.ray"></context:component-scan>
</beans>
使用@Configuration表示你是一个配置类,使用@ComponentScan(value = {"com.ray"}),配置需要扫描的包。
package com.ray.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(value = {"com.ray"})
public class SpringConfig {
}
测试类的写法有变化AnnotationConfigApplicationContext(SpringConfig.class)
public class UserTest {
@Test
public void testService(){
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
Service service = context.getBean("service", Service.class);
service.service();
}
}