package com.springboot.chapter3.pojo;
public class User {
private Long id;
private String userName;
private String note;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
package com.springboot.chapter3.config;
import com.springboot.chapter3.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/*@Configuration代表这是一个Java配置文件,Spring的容器会根据它来生成IoC容器去装配Bean*/
@Configuration
public class AppConfig {
/*@Bean代表将initUser方法返回的POJP装配到IoC容器中,其属性name定义了这个Bean的名称,
如果没有配置它,则将方法名称“initUser”作为Bean的名称保存到Spring IoC容器中*/
@Bean(name = "user")
public User initUser() {
User user = new User();
user.setId(1L);
user.setUserName("user_name_1");
user.setNote("note_1");
return user;
}
}
package com.springboot.chapter3.config;
import com.springboot.chapter3.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.logging.Logger;
public class IoCTest {
private static Logger log = Logger.getLogger(String.valueOf(IoCTest.class));
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
User user = ctx.getBean(User.class);
log.info(user.getUserName());
}
}