spring配置
1、导入jar包
<!--spring5.x的jar包-->
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.4.RELEASE</version> </dependency>
2、配置applicationContext.xml
id为每一个bean的唯一标识,可写可不写。
<bean>标签中可以给需要创建的类的构造方法初始化值
<bean class="redis.clients.jedis.JedisPool">
<constructor-arg name="host" value="192.168.1.102"/>
<constructor-arg name="port" value="6379"/>
</bean>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--默认方法创建对象,单例方法。对象初始化的时候调用方法--> <bean id="studentService" init-method="init" class="com.shankai.text"/> <!--bean后处理器--> <!--<bean id="post" class="com.shankai.proxy.PodtProxy"/>--> </beans>
这种编写配置文件的方式可以被注解代替:@Configuration @Bean
@Configuration
@ComponentScan(value = "com.sk")
public class MyConfig { @Bean public text studentService() { return new text(); } }
@ComponentScan注解代表的是下面这个xml配置文件:包扫描器
<context:component-scan base-package="com.sk"></context:component-scan>
3、创建测试类,无需new对象,测试容器中是否有该bean(xml配置方式)。
ApplicationContext classPath = new ClassPathXmlApplicationContext("applicationContext.xml"); UserServiceImpl bean = (UserServiceImpl) classPath.getBean("UserService"); bean.addUser();
这种方式获取的对象是单例的。
可以使用@scope注解改变。
该注解主要有两个值:
prototype:多个实例,每次调用bean的时候都会创建对象。
singleton:单例,ioc容器启动时候就创建对象放到容器中,每次调用,从容器中调用同一个实例,可以使用@lazy注解实现懒加载【容器启动时候不创建对象,而是调用的时候】。
@Conditional 注解按照条件进行动态装配,可以标记在方法上,也可以标记在类上。
只有满足Conditional中的条件,该注解下的类或者方法才进行装配。
@import(导入的组件名) 快速给容器中导入组件 ,id就是全类名。
@Profile :根据环境注册bean,可以设置成默认的 @Profile(”default“),也可以设置成自定义的 @Profile(”xxxx“)。
在启动的时候加上命令行参数-Dspring.profiles.active=xxxx即可注册该注解下的bean。

浙公网安备 33010602011771号