前言:spring在使用注解功能时候,有两种方式
一:xml配置文件+注解;
二:完全注解,没有xml配置文件
一、xml配置文件+注解(半完全注解开发)
在application.xml配置文件中,需要类似这样的
<context:component-scan base-package="com.baidu">
</context:component-scan>
扫描包,用来开启注解。
然后就可以在类上、属性上、方法上加注解了。
测试main方法:
public static void main(String[] args) {
//加载xml配置文件 启动IOC容器
ApplicationContext context=new ClassPathXmlApplicationContext("application.xml");
//获取bean
UserService userService=context.getBean("userService",UserService.class);
}
二、完全注解(完全注解开发)
不需要xml配置文件,
而是写一个配置类《====》替代xml配置文件
/**
* spring的配置类 替代了 Spring的xml配置文件
*/
@Configuration //作为配置类 替代xml配置文件
@ComponentScan(basePackages = {"com.abc"}) //替代xml配置文件中的<context:component-scan>
public class SpringConfig {
}
测试main方法:
public static void main(String[] args) {
//加载配置类 启动IOC容器
ApplicationContext context=new AnnotationConfigApplicationContext(SpringConfig.class);
//获取bean
UserService userService=context.getBean("userService",UserService.class);
}