spring的启动方式

直接在xml里面装配bean

spring,我们大家最开始接触的版本,是2.x的

   ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
   UserService us = (UserService) ac.getBean("userService");
   us.sayHello();

其中的配置文件类似

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
    <bean id="userService" class="com.jason.services.UserService">
      <property name="name">
        <value>jason</value>
      </property>
    </bean>
</beans>

加入扫描器

之后有了扫描器,可以少加一些配置文件
有了扫描器之后,配置文件就类似

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd">

    <context:component-scan base-package="com.example.scan" />
</beans>

然后在需要配置的组件上加上 @service,@Repository即可

配置类装配

再之后就有了配置类

/**
 * 通过扫描批量注册加了组件注解的bean
 */
@Configuration
@ComponentScan(basePackages = {"com.example.scan"})
public class BeanConfig {
}

容器的初始化就又变成了,此时已经没有xml了

ApplicationContext ctx = new AnnotationConfigApplicationContext(BeanConfig.class);

参考资料

最基本的xml
加了扫描器的xml
使用配置类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值