Spring简介

Spring简介

  1. Spring 能做啥??? “简化项目”
  2. 为了降低Java开发的复杂性,Spring采取了以下4种关键策略:
    • 基于POJO的轻量级和最小侵入性编程;
    • 通过依赖注入和面向接口实现松耦合;
    • 基于切面和惯例进行声明式编程;
    • 通过切面和模板减少样板式代码。
  3. spring容器配置bean的方式
    1、基于xml的配置
    2、基于java的显示配置
    @Configration
    定义配置类
    @Bean
    定义方法
    3、自动配置
    @Component 定义bean
    @ComponentScan 启动扫描
    @AutoWrite 注入属性
    @Qualifier 指定注入那个bean
  4. 具体使用
    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的显式配置==。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值