pom依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.kgcSpring</groupId>
<artifactId>Spring0101</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>spring-02-hellospring</module>
<module>spring-03-ioc2</module>
<module>spring-04-ioc3</module>
<module>spring-05-ioc4</module>
<module>spring-06-ioc5</module>
<module>spring-07-ioc6</module>
</modules>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
</dependency>
</dependencies>
</project>
实体类
package com.kuang.pojo;
import org.springframework.beans.factory.annotation.Value;
public class User {
@Value("狂神小迷弟")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
配置类
package com.kuang.config;
import com.kuang.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;
//这个也会被spring容器托管,注册到容器中,因为他本来就是一个@Component
//@Configuration 代表了一个配置类,就和我们之前的beans.xml一样
@Configuration
@ComponentScan("com.kuang.pojo")//扫描包
@Import(KuangConfig2.class)
public class KuangConfig {
//注册bean, 就相当于我们之前写的一个bean标签
//这个方法的名字,就相当于bean标签中的id的属性
//这个方法的返回值,就相当于bean标签中的class属性
@Bean
public User user(){
return new User();
}
}
package com.kuang.config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class KuangConfig2 {
}
测试类
import com.kuang.config.KuangConfig;
import com.kuang.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MyTest {
@Test
public void cc(){
//如果完全使用了配置类方式去做,我们就只能通过 AnnotationConfig 上下文来获取容器
//通过配置类的class对象加载
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(KuangConfig.class);
User getUser = context.getBean("user", User.class);
// User getUser = context.getBean( User.class); 获取bean的方式 两种都行
System.out.println(getUser.getName());
}
}
用AnnotationConfigApplicationContext的原因 看下面源码
补充官方源码