Java-Spring框架(一)续

200 阅读2分钟

Bean对象的作用域:

指定Spring容器创建Bean对象的作用域:

            

注意:

singleton单例模式,通过getBean获取的对象HashCode是相同的,即user1 = user2返回true,
prototype多例模式,通过getBean获取的对象HashCode是不同的,即user1 = user2返回false
Bean对象的参数注入: (看上面的applicationContext.xml中注释写的知识点)
容器可以建立Bean对象之间的关系,实现技术途径就是DI注入,Spring DI注入setter注入和构造器注入两种
组件扫描: Spring提供了一套基于注解配置的的使用方法,使用该方法可以大大简化XML的配置信息

开启组件扫描,可以利用注解方式应用IOC,使用方法如下:

**第一步:** 除了需要引入springIOC相关jar包之外还需要引入SpringAOP相关jar包

                

  第二步: 在applicationContext.xml中添加启用标记(用了组件扫描就可以不用bean标签了)

       <context:component-scan base-package="包路径(用最大的,例如:com.springioc)"/>

 第三步: 在组件类中追加以下标记

              

注意: 1.扫描组件后,默认id值为组件类名首字母小写,也可以自定义id。例如:@Component("stu")

2.扫描组件后,默认scope为singleton单例,也可以进行指定。例如:@Scope("prototyppe")

3.也可以指定初始化和销毁的方法,例如,在组件类的方法前追加@PostConstruct来指定初始化方法,追加@PreDestory来指定销毁方法

4.将所有bean组件扫描到Spring容器后,可以使用以下注解指定注入关系  @Resource:只能处理Setter注入,但大部分情况都是setter注入

5.@Value注解可以注入Spring表达式值  首先读取db.properties文件,封装成Properties对象,在applicationContext.xml中添加

<util:properties id="jdbc" location="classpath:jdbc.properties"></util:properties>

然后在组件类属性变量或Setter方法前使用@Value注解

 @Value("#{db.url}")

private String url;

              追加标记举例:

1 @Component//默认实体类id名称是实体类名称(首字母小写)
2 @Scope("prototype")//默认为单例模式,此处修改为多例模式
3 public class User {
4 }

第四步: 测试获取bean对象: package com.springioc.test;

import org.springframework.context.ApplicationContext;//spring-context.jar包中的 import org.springframework.context.support.ClassPathXmlApplicationContext;//spring-context-support.jar包中的

import com.springioc.entity.User;

public class ApplicationContextBuildUserTest { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = ac.getBean("user", User.class);//此处的id:user是从@Component默认实体类id中得出来的 System.out.println(user); } }

运行结果: