package com.iflytek.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
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.iflytek.config;
import com.iflytek.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//相当于applicationContext.xml
@Configuration
@ComponentScan("com.iflytek.pojo")
public class UserConfig {
//注册一个bean,就相当于我们之前写的一个bean标签
//这个方法的名字,就相当于bean标签中的id属性
//这个方法的返回值类型,就相当于bean标签中的class属性
@Bean
public User getUser(){
return new User();//就是返回要注入到bean的对象!
}
}
import com.iflytek.config.UserConfig;
import com.iflytek.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestDemo {
public static void main(String[] args) {
/*用配置类做的话,需要使用AnnotationConfigApplicationContext 上下文来获取容器
通过配置类的class对象加载!*/
ApplicationContext context = new AnnotationConfigApplicationContext(UserConfig.class);
User getUser = (User) context.getBean("getUser");
System.out.println(getUser.getName());
}
原文:https://www.cnblogs.com/rswpc/p/14471387.html