pom依赖
实体类4.0.0 com.kgcSpring Spring0101pom 1.0-SNAPSHOT spring-02-hellospring spring-03-ioc2 spring-04-ioc3 spring-05-ioc4 spring-06-ioc5 spring-07-ioc6 org.springframework spring-webmvc5.3.18 org.springframework spring-jdbc5.3.18 junit junit4.13.1
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的原因 看下面源码
补充官方源码



