Spring全注解开发不使用xml文件
-
配置类
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; //表明为一个配置类 @Configuration //扫描包 @ComponentScan(basePackages = {"com.dragon"}) public class ConfigAop { }
这里的配置类就相当于我们的xml文件
-
声明组件
import org.springframework.stereotype.Component; //user0相当于id @Component(value = "user0") public class User { public void add(){ System.out.println("add添加...."); } }
这里的组件就是
标签 <bean id="user0" class="com.xxx.xxx.User"> </bean>
-
测试
@Test public void test(){ ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ConfigAop.class); User user = applicationContext.getBean("user0", User.class); user.add(); }
注意这里是 AnnotationConfigApplicationContext,并不是ClassPathXmlApplicationContext
加载文件是ConfigAop.class,并不是xxx.xml