Spring入门讲解
    		       		warning:
    		            这篇文章距离上次修改已过422天,其中的内容可能已经有所变动。
    		        
        		                
                Spring是一个开源的Java平台,提供了一整套解决方案,包括控制反转(IoC)和面向切面编程(AOP)等。
以下是一个简单的Spring入门示例,演示如何使用Spring来注入依赖。
首先,在pom.xml中添加Spring核心依赖:
<dependencies>
    <!-- Spring Core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.20</version>
    </dependency>
    <!-- Spring Context -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.20</version>
    </dependency>
</dependencies>创建一个接口和实现类:
public interface GreetingService {
    void sayHello(String name);
}
 
@Component
public class GreetingServiceImpl implements GreetingService {
    public void sayHello(String name) {
        System.out.println("Hello, " + name + "!");
    }
}创建Spring配置文件(applicationContext.xml):
<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">
 
    <context:component-scan base-package="com.example.demo" />
 
</beans>最后,使用Spring容器并获取Bean:
public class App {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        GreetingService greetingService = context.getBean(GreetingService.class);
        greetingService.sayHello("World");
    }
}在这个例子中,我们定义了一个简单的GreetingService接口和它的实现类GreetingServiceImpl。我们使用@Component注解将GreetingServiceImpl标记为Spring管理的组件。然后,在applicationContext.xml中通过<context:component-scan>启用组件扫描,以便Spring发现并注册这个组件。最后,在App类的main方法中,我们创建了一个ApplicationContext,它是Spring的核心接口,用于配置和管理应用程序对象(Bean)。我们通过该接口获取了GreetingService的实例,并调用了sayHello方法。
评论已关闭