Spring 使用java和注解开发,不使用beans.xml

congig配置类

//这个也会被Spring容器托管,注册到容器中,以为他本来就是一个@ComponentScan
//@Configuration代表这是一个配置类,就是我们之前看到的beans.xml
@Configuration
@ComponentScan("com.liu.pojo")可以配合扫描使用

package com.liu.config;

import com.liu.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


//这个也会被Spring容器托管,注册到容器中,以为他本来就是一个@ComponentScan
//@Configuration代表这是一个配置类,就是我们之前看到的beans.xml
@Configuration
@ComponentScan("com.liu.pojo")
public class UserConfig {



    //等价于生成一个  id=“getUser”,class = com.liu.pojo.User
@Bean
    public User getUser(){
        return new User();
    }
}

pojo

需要//@Component注册到容器中

package com.liu.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

//@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 + '\'' +
                '}';
    }
}

测试

需要用new AnnotationConfigApplicationContext(UserConfig.class)

import com.liu.config.UserConfig;
import com.liu.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext Context = new AnnotationConfigApplicationContext(UserConfig.class);
        User getUser = Context.getBean("getUser", User.class);
        System.out.println(getUser);
    }
}
posted @   小幼虫虫  阅读(38)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示