1.Spring里,默认bean是单实例对象
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml"); User user1 = context.getBean("user", User.class); User user2 = context.getBean("user",User.class); System.out.println(user1.equals(user2)); //输入true,user1 = user2
Spring配置文件bean标签外面有属性scope用于设置单实例还是多实例
(1)singleton:默认值、单实例
(2)prototype:多实例
<!-- id:实例化对象的惟一标识; class:类的全门路 --> <bean id="user" class="com.dk.entity.User" scope="prototype"> <!--属性注入:name示意属性名称,value示意属性值--> <property name="name" value="LiHui"></property> <property name="age" value="25"></property> </bean>
tips:
当应用Lombok的@Data注解时,则有了@EqualsAndHashCode注解,那么就会在此类中存在equals(Object other) 和 hashCode()办法,且不会应用父类的属性。如果两个对象的属性雷同,就会认为这两个对象相等,即重写了hashCode和equls办法。
2.Bean的生命周期
(1)通过结构器创立Bean实例(无参数结构)
(2)为Bean的属性设置值和对其余Bean进行援用(调用Set办法)
(3)调用Bean的初始化办法
(4)获取Bean对象
(5)容器敞开时,调用Bean的销毁办法
3.主动拆卸
什么是主动拆卸:
依据属性名称和属性类型,主动将匹配的属性值进行注入
通过xml文件
bean标签中autowire = "byName" / "byType"
通过注解形式
步骤:
(1)引入依赖:spring-aop.jar
(2)开启组件扫描:
<!-- 控件扫描--> <context:component-scan base-package="demo"></context:component-scan>
<!--局部扫描--><context:component-scan base-package="com.dk" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan>
(3)创立类,在类下面增加创建对象注解
(1)@Component:一般组件(2)@Service:业务逻辑层或service层(3)@Controller:web层(4)@Repository:view层或dao层
(4)基于注解形式实现属性注入
(1)@Autowired:依据属性类型进行主动拆卸(2)@Qualifier:依据属性名称进行注入(和@Autowired一起应用)(3)@Resource:能够依据类型,也能够依据名称(4)@Value:注入一般类型属性值