xml配置
优势:集中配置,代码配置分离更加方便管理
劣势:繁杂,编译期不容易发现错误
javaConfig配置
优势:代码简洁,
劣势:国内xml配置方式比较多,不容易被人接受
最简单的spring xml配置,但是使用javaConfig只需要@Configuration一个注解. 而其中的<bean>标签作用类似于下面的@Bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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-4.0.xsd
http://www.springframework.org/schema/context">
<bean id="cat" class="com.spmjava.model.cat/>
</beans>
使用步骤:
1.配置类上写上注解@Configuration标识这个类是一个配置类
2.通过ComponentScan扫描装载自定义Bean(bean上得配置有@Component等注解)
@ComponentScan(basePackages = {"com.spmjava.model"})
@Configuration
public class PersonConfig {
}
@Component
public class Person{
}
3.使用@Bean注解创建第三方bean,创建的bean id是getCat
@Bean
public Cat cat(){
return new Cat();
}
4.在web.xml配置