Spring框架是由于软件开发的复杂性而创建的
目的:解决企业应用开发的复杂性
功能:使用基本的JavaBean代替EJB,并提供了更多的企业应用功能
范围:任何Java应用
优点:
开源的免费的框架(容器)
Spring是一个轻量级、非入侵式的框架
控制反转(IOC)和面向切面(AOP)的容器框架
支持事务的处理,对框架整合的支持
官网:https://spring.io/
GitHub:https://github.com/spring-projects/spring-framework
Maven
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
IoC 全称为 Inversion of Control
,即“控制反转”,Spring 的核心内容之一,是一种通过描述(xml 或 注解)并通过第三方获取特定对象的方式,Spring 中实现控制反转的是 IoC 容器,其实现方式是 DI(Dependency Injection
),即依赖注入。
通过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/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="he" class="com.youzi.pojo.Hello">
<property name="Str" value="Hello Spring!"/>
</bean>
</beans>
public class Hello {
private String Str;
public Hello(String str) {
Str = str;
}
public Hello() {
}
public String getStr() {
return Str;
}
public void setStr(String str) {
Str = str;
}
}
...
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Object he = context.getBean("he");
System.out.println(he);
}
<bean id="userservice" class="com.youzi.service.UserServiceImpl">
<property name="user" ref="user"/>
</bean>
<bean id="user" class="com.youzi.dao.UserImpl"/>
以上方式调用了对应类中的无参构造和 setter,即需要初始化的参数或者对象必须有对应的 setter,如果要调用有参构造可以使用 <constructor-arg>
通过类型、下标、参数名字、引用这几种方式传参
public Users(Hello hello, String num) {
this.hello = hello;
this.num = num;
}
<bean id="users" class="com.youzi.pojo.Users">
<!--<constructor-arg type="java.lang.String" value="1"/>-->
<!--<constructor-arg index="1" value="2"/>-->
<constructor-arg name="num" value="3"/>
<constructor-arg ref="he"/>
</bean>
name
创建)
<bean id="he" class="com.youzi.pojo.Hello" name="hello3,hello4">
<property name="Str" value="Hello Spring!"/>
</bean>
<alias name="he" alias="hello1"/>
<alias name="he" alias="hello2"/>
bean 对象默认创建的为单例模式,可以通过
scope="prototype"
修改,这样 hello3,hello4 就是两个不同的对象了
上面只是基本的配置,每个配置里面还有很多的细节配置待以后再进一步的学习
原文:https://www.cnblogs.com/wangjr1994/p/12514704.html