0
点赞
收藏
分享

微信扫一扫

spring的启动方式


直接在xml里面装配bean

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

= 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);

举报

相关推荐

0 条评论