赞
踩
1.创建实体类:User
- package com.huahua.pojo;
-
- import jdk.nashorn.internal.objects.annotations.Constructor;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.stereotype.Component;
-
- import java.beans.ConstructorProperties;
-
- //这个注解的意思,就是说这个类被spring接管,注册到了容器中
- @Component
- public class User {
- @Value("123")
- private String name;
- @Value("23")
- private int age;
-
- public User() {
-
- }
-
-
- @Override
- public String toString() {
- return "User{" +
- "name='" + name + '\'' +
- ", age=" + age +
- '}';
- }
-
- public User(String name, int age) {
- this.name = name;
- this.age = age;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
- }
2.创建配置类:
- package com.huahua.config;
-
- import com.huahua.pojo.User;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.ComponentScan;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.stereotype.Controller;
- //@Configuration 代表这是一个配置类
- @Configuration
- @ComponentScan("com.huahua")//扫描包下面的注释
- public class Config {
- //注册一个bean 相当于一个bean标签
- //这个方法的名字 这个bean的id
- //这个方法的返回值 就是bean的class
- @Bean
- public User getUser(){
- return new User();
- }
-
- }
2.创建测试类:
- package com.huahua;
-
- import com.huahua.config.Config;
- import com.huahua.pojo.User;
- import org.junit.Test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.annotation.AnnotationConfigApplicationContext;
-
- public class MyTest {
- @Test
- public void test(){
- ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
- User getUser = context.getBean("getUser", User.class);
- System.out.println(getUser.toString());
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。