欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java 如何使用@Autowired注解自动注入bean

程序员文章站 2022-03-11 12:31:46
java @autowired注解自动注入beanannotationwire.xml (一定记得配置context:annotation-config/)

java @autowired注解自动注入bean

annotationwire.xml (一定记得配置context:annotation-config/)

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config/>
    <bean id="order" class="com.annotationwire.pojo.order" p:order="202020124546" />
    <bean id="user" class="com.annotationwire.pojo.user" />
</beans>

user类

package com.annotationwire.pojo;
import lombok.data;
import org.springframework.beans.factory.annotation.autowired;
@data
public class user {
    private string name;
    @autowired
    private order order;
}

order类

package com.annotationwire.pojo;
import lombok.data;
@data
public class order {
    private string order;
}

测试类

package com.annotationwire;
import com.annotationwire.pojo.user;
import org.junit.test;
import org.springframework.context.applicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;
public class testannotation {
    @test
    public void test(){
        applicationcontext applicationcontext = new classpathxmlapplicationcontext("annotationwire.xml");
        user student = applicationcontext.getbean(user.class);
        system.out.println(student);
    }
}

java配置spring,无法@autowired自动注入bean的问题

要在配置类上加上@componentscan

同时在rootconfigure和servletconfig两个类上scan的对象是不同的

servletconfig是用来注册dispatcherservlet的,它只是用来扫描controller层的

rootconfigure用来注册contextloaderlistener,他扫描的范围是除了controller以外的bean,例如dao,service,bean实体。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。