Spring 是于2003 年兴起的一个轻量级的Java 开发框架,它是为了解决企业应用开发
的复杂性而创建的。Spring 的核心是控制反转(IoC)和面向切面编程(AOP)。Spring 是可
以在Java SE/EE 中使用的轻量级开源框架。
控制反转(IoC,Inversion of Control),是一个概念,是一种思想。指将传统上由程序代
码直接操控的对象调用权交给容器,通过容器来实现对象的装配和管理。控制反转就是对对
象控制权的转移,从程序代码本身反转到了外部容器。通过容器实现对象的创建,属性赋值,
依赖的管理。
使用spring需要的配置
一:引入maven的依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.5.RELEASE</version> </dependency> 插件 <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build>
二:创建spring配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!--组件扫描器 用于指定的基本包中扫描注解 --> <context:component-scan base-package="com"></context:component-scan> <bean id="stu" class="com.w9420.entity.Student"> <property name = "name" value= "小明"></property> <property name = "age" value= "100"></property> <property name = "id" value= "1001"></property> </bean> <bean id="school" class="com.w9420.entity.School"> <property name = "id" value= "1"></property> <property name = "name" value= "小学一年级"></property> <property name="stu" ref="stu"></property> </bean> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>
常用注解:
@Component 一般使用在bean类上和工具类上等。
@Service 用于对Service实现类进行注解 业务层对象可以加入事务功能
@Repository 用于对Dao实现类进行注解
@Controller 用于对Controller 实现类进行注解 处理器接收用户的请求
@Value 用于指定要注入的值(可以加在set方法上)
@AutoWired 按类型自动装配bean的方式 (可以加在set方法上)
Autowired还有一个属性required,默认值为true,表示当匹配失败后,会终止程序运
行。若将其值设置为false,则匹配失败,将被忽略,未匹配的属性值为null。
@Qualifier 需要和AutoWired联合使用 它的value属性用于指定匹配bean的id值(可以加在set方法上)
@Resource 注解若不带任何参数,采用默认按名称的方式注入,按名称不能注入bean,则会按照类型进行Bean 的匹配注入。
原文:https://www.cnblogs.com/w5920/p/14531403.html