Spring简介
- Spring 能做啥??? “简化项目”
- 为了降低Java开发的复杂性,Spring采取了以下4种关键策略:
- 基于POJO的轻量级和最小侵入性编程;
- 通过依赖注入和面向接口实现松耦合;
- 基于切面和惯例进行声明式编程;
- 通过切面和模板减少样板式代码。
- spring容器配置bean的方式
1、基于xml的配置
2、基于java的显示配置
@Configration
定义配置类
@Bean
定义方法
3、自动配置
@Component 定义bean
@ComponentScan 启动扫描
@AutoWrite 注入属性
@Qualifier 指定注入那个bean - 具体使用
1,创建容器
xml:ClassPathXmlApplicationContext ct = new ClassPathXmlApplicationContext(xml配置文件);
基于java、自动配置
AnnotationConfigApplicationContext ct = new AnnotationConfigApplicationContext(配置类.class);
2,从容器中获取bean
容器.getBean(“id”);
容器.getBean(bean.class);
3,销毁容器
容器.close()
自动配置
public interface StudentDao {
public void select();
}
@Component("mysqlDao")
public class StudentImpl implements StudentDao {
public void select() {
System.out.println("mysql查询中!");
}
}
@Component("oracleDao")
public class StudentImploracle implements StudentDao {
public void select() {
System.out.println("oarcle 查询中");
}
}
@Component("StuBiz")
public class StudentService {
//定义dao 对象
@Autowired //当前属性需要自动注入
@Qualifier("oracleDao") //注入的类型
private StudentDao dao;
//服务方法
public void service() {
dao.select();
}
}
@Configuration
@ComponentScan
public class test {
//不需要配置xml文件
public static void main(String[] args) {
//获取spring容器
AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(test.class);
//从spring容器中获取对象
StudentService biz = (StudentService) ctx.getBean("StuBiz");
biz.service();
ctx.close();
}
}
- @Component用来声明哪些bean需要由spring容器进行管理
- @ComponentScan用来对声明了@Component的类启用组件扫描,spring将会扫描=>这个包以及这个包下的所有子包
- @Autowired实现自动装配
在上述用例中,我们看到了Spring中装配Bean的三种主要方式:自动化配置、基于Java的显式配置以及基于Xml的显式配置。不管采用什么方式,这些技术都描述了Spring应用中的组件以及这些组件之间的关系。同时,建议尽可能使用自动化配置,以避免显式配置所带来的维护成本。从选择配置方式的优先级来看,建议按照以下顺序:自动化配置–>基于Java的显式配置–>基于Xml的显式配置==。