现在我们尝试不使用Spring的XML文件来配置了,全权交给Java来做
1 编写pojo类
这个类要被Spring接管,要被注册到容器中
- 添加
@Component
注解- 通过
@Value
注解来为属性注入值
package com.wq.pojo;import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;@Component
public class User {@Value("光头强")private String name;@Value("20")private int age;@Overridepublic String toString() {return "User{" +"name='" + name + '\'' +", 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 编写config类
新建config包
编写config类
为这个类添加@Configuration
注解,表示这个类也会被spring托管
package com.wq.config;import com.wq.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class WqConfig {@Beanpublic User getUser(){return new User();}
}