1、pom.xml依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.6.RELEASE</version> </dependency>
2、实体类
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class Person { private String name; private int age; }
3、配置类
import com.it.vo.Person; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class PersonConfig { @Bean public Person person() { return new Person("刘正", 31); } }
4、测试类
import com.it.config.PersonConfig; import com.it.vo.Person; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class PersonTest { public static void main(String [] args) { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfig.class); Person person= (Person)applicationContext.getBean("person"); System.out.println(person); } }
//结果:Person(name=刘正, age=31)