spring1
Spring Ioc/id:
控制反转/依赖注入,两个东西名字不一样,但实际上是一个东西,创建对象的权利,或者是控制的位置,由java代码转移到spring容器中,由spring的容器控制对象的创建,就是控制反转
程序的分层:
大致可以分成三层:三层的ssm框架也是由此来(springmvc,spring,mybatis)
控制层(获取前端的数据,进行业务的跳转,调用业务层),业务层(处理业务,调用持久层),持久层(更数据库进行交互)
spring:
1.创建项目,添加依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.2.7</version>
</dependency>
导入spring-context,这个jar包依赖了四个必备的jar包,导一个就够了
2.创建一个类
3.创建spring配置文件
在resources下新建application.Context.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="b" class="com.zrt.pojp.Book"></bean>
</beans>4.创建容器,测试
public class Test {public static void main(String[] args) {//创建spring容器ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");//获取对象Book book = (Book)context.getBean("b");System.out.println(book);}
}属性注入:
setter方法:设值注入 构造器赋值:构造注入
设值注入:
<bean id="b" class="com.zrt.pojp.Book">
//注意这里的id和name是set方法中的方法名后的名字,而不是变量名
也就是说方法名set()这个name就为 什么<property name="id" value="1"></property><property name="name" value="活着"></property></bean>构造注入:
<bean id="b2" class="com.zrt.pojp.Book"><constructor-arg name="id" value="2"></constructor-arg><constructor-arg name="name" value="红高粱"></constructor-arg></bean>注入对象:
<bean id="Boy" class="com.zrt.pojp.Boy"><constructor-arg name="age" value="16"></constructor-arg><constructor-arg name="name" value="mm"></constructor-arg></bean><bean id="Girl" class="com.zrt.pojp.Girl"><constructor-arg name="age" value="16"></constructor-arg><constructor-arg name="name" value="lili"></constructor-arg>
//注意这里的ref<constructor-arg name="boyfriend" ref="Boy"></constructor-arg></bean>注解:
框架=注解+反射+设计模式
这些注解标记可以在编译,类加载,运行时被读取,可以有效代替一些繁冗代码和xml配置
Ioc/DI相关注解:
@component:实例化Bean,默认名称为类名首字母小写,无需指定setter方法
在使用的时候要对componen在配置文件中进行扫描
xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsd"><context:component-scan base-package="com.zrt.pojp"></context:component-scan>@repository:作用和component一样用于持久层
@service:作用和component一样用于业务层
@controller:作用和component一样用于控制器层
@configuration:作用和component一样用于配置类上
@autowired:自动注入。默认byType,如果同类型bean,使用byName,不需要setter方法
@value:给普通数据类型属性赋值,不需要setter方法
@Value("18")private int age;@Value("lili")private String name;@Autowiredprivate Boy boyfriend;