Spring不使用XML的注解开发

这里不再用XML配置,直接用纯Java配置,首先是写一个User实体类

package com.zhiying.pojo;

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

public class User {
    private String name;

    public String getName() {
        return name;
    }

    @Value("贺志营")
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                '}';
    }
}

按照惯例需要写配置文件,但是这里不用配置文件了,所以写一个Java配置类

package com.zhiying.config;

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

//这里如果有多个配置文件,也可以用@Import()引入
//例如引入MyConfig2注解只需在类上面写@Import(MyConfig2.class)

//该注解会被Spring托管,注册到容器中,他该表这是一个配置类,相当于我们的applicationContext.xml
@Configuration
public class MyConfig {

    //注册一个bean,就相当于我们之前写的一个bean标签,这个方法中的名字,就相当于bean标签中的id
    @Bean
    public User user() {
        return new User(); //返回要注入到bean的对象
    }
}

进行测试

import com.zhiying.config.MyConfig;
import com.zhiying.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(MyConfig.class);
        User user = (User) context.getBean("user");
        System.out.println(user.getName());
    }
}

发布了376 篇原创文章 · 获赞 242 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/HeZhiYing_/article/details/103943630