spring:入门

144 阅读3分钟

介绍

  1. spring:是一个轻量级的框架(非侵入式)
  2. IOC:Inversion of Control 控制反转 控制反转:对象的创建不再由程序员控制,而交给spring的IOC容器创建,对象是由spring框架帮程序员创建,什么时候创建,创建什么都是spring的IOC容器说了算,控制权在IOC容器手上
Student student;
xml <bean></bean>
  1. IOC容器:存放、管理对象
  2. 控制正转:所有需要的对象,都是由程序员通过new方法创建出来的,对象创建的控制权在程序员手上。
Student student= new Student();什么时候要,要什么都是程序员决定的
  1. DI:Dependency Injection 依赖注入 IOC容器将程序中需要的对象主动给需要的地方 依赖:
    class A(){
        void fun(B b){
          //A依赖B  
        }
    }

  1. IOC与DU是同一种事物,站在不同的角度来看待,IOC是一种设计思想。

用法

  1. applicationContext.xml的配置

    a. 添加文件约束

    <?xml version="1.0" encoding="UTF-8"?>
    

``` b. 对要通过spring获取的bean类:在上述文件前添加:

```
	<!-- 默认调用无参构造方法 -->
        <!-- lazy-init:使用时再创建 -->
<bean	id="user" class="com.dyr.bean.User" lazy-init="true"></bean>


<!-- 利用setter给属性赋值 
	scope:
		singleton	单例
		prototype	多例
		request		每一次请求都会创建一个
		session		每一次请求都会创建一个bean,但是在同一个session中只会存在一个
-->
<bean id="u1" class="com.dyr.bean.User" scope="prototype">
	<property name="uid" value="123"></property>
	<property name="uname" value="456"></property>
</bean>

<!-- 利用有参构造方法创建对象 -->
<bean id="u2" class="com.dyr.bean.User">
	<constructor-arg name="uid" value="666"></constructor-arg>
	<constructor-arg name="uname" value="888"></constructor-arg>
</bean>
```
c. 简单使用

```
public static void main(String[] args) {
	//1.加载spring的主配置文件
	ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
	//2.通过ac获取想要的对象,通过对象id拿到对象(加载就创建了对象)
	User user = (User) ac.getBean("u2");
	//以类型获取对象,要求xml中该类型的对象只有一个
	user = ac.getBean(User.class);
	user = ac.getBean("user", User.class);
	
/*	String[] names = ac.getBeanDefinitionNames();//返回所有bean的名字,就是在xml文件中对象的id*/
	System.out.println(user);
	//其创建的对象只有一个
	User u1 = ac.getBean("u1",User.class);
	User u2 = ac.getBean("u1",User.class);
	System.out.println(u1);
}
```
  1. 导包 commons-logging-1.2.jar spring-aop-4.3.10.RELEASE.jar spring-beans-4.3.10.RELEASE.jar spring-context-4.3.10.RELEASE.jar spring-core-4.3.10.RELEASE.jar spring-expression-4.3.10.RELEASE.jar

注解方式

  1. 结构:action、service、dao均实现接口Interface。同名方法调用下一层的同名方法,直到dao层操作数据库。等价于在xml中配置了一个bean
  2. 使用注解,需要在主配置文件applicationContext中,在最后配置:
<!-- 如果使用了注解,要开起注解扫描 -->
	<context:component-scan base-package="com.dyr.annotation"></context:component-scan>
  1. 配置方法,在类上添加@Component("xxxAction"),为了便于分辨可在:action类上添加@Controller("xxxAction"),service类上添加@Service("service"),dao类上添加@Repository 对于类中的属性:@Resource(name="service")也可默认@Resource,以名字去找
  2. 类上注解的名字就是其他地方使用该类对象的对象名