IDEA+Maven+Spring5.X项目创建

    科技2022-07-10  116

    Spring 核心概念

    IoC(核心中的核心):Inverse of Control,控制反转。对象创建的权利由程序员交给Spring框架AOP:Aspect Oriented Programming,面向切面编程。在不修改目标对象的源代码情况下,增强IoC容器中Bean的功能DI:Dependency Injection,依赖注入。在Spring框架负责创建Bean对象时,动态的将依赖对象注入到Bean组件中!!Spring容器:就是IoC容器

    1.添加依赖

    <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.5.RELEASE</version> </dependency> </dependencies>

    2.添加配置文件applicationContext.xml

    在src/main/resources下创建applicationContext.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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="video" class="net.cybclass.sp.domain.Video"> <property name="id" value="9"></property> <property name="title" value="Spring5.X课程"></property> </bean> </beans>

    bean标签

    id属性:指定Bean的名称,在Bean被别的类依赖时使用name属性:用于指定Bean的别名,如果没有id,也可以用nameclass属性:用于指定Bean的来源,要创建Bean的class类,需要全限定名

    3.创建Video.java 

    package net.cybclass.sp.domain; /** * @author: wangxiaobo * @create: 2020-10-03 15:08 **/ public class Video { private int id; private String title; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }

    4.创建app.java

    package net.cybclass.sp; import net.cybclass.sp.domain.Video; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author: wangxiaobo * @create: 2020-10-03 15:11 **/ public class app { public static void main(String[] args) { ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); Video video=(Video) applicationContext.getBean("video"); System.out.println(video.getTitle()); } }

    5.运行

    Processed: 0.031, SQL: 8