Spring入门-输出HelloWorld
平常我们创建类时是自己通过new对象来实现。Spring容器则可以帮我们创建对象。
官网学习链接:The IoC Container
一、创建一个Maven项目
二、导入坐标
在pom.xml
加入如下坐标。并且点击右上角的刷新。等待jar下载完毕。
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.15</version>
</dependency>
</dependencies>
三、测试
创建一个Bean类,名为HelloImpl
public class HelloImpl {
public void sayHello() {
System.out.println("Hello World");
}
}
创建容器类AppConfig
。在该类上加入@Configuration
注解,用来托管Bean。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public HelloImpl helloImpl(){
return new HelloImpl();
}
}
创建一个Test类,用来测试。
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
HelloImpl hi = (HelloImpl)ac.getBean("helloImpl");
hi.sayHello();
}
}
文章版权声明:除非注明,否则均为彭超的博客原创文章,转载或复制请以超链接形式并注明出处。
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。