java怎么拦截某个对象
279
2023-01-06
Java 如何使用@Autowired注解自动注入bean
java @Autowired注解自动注入bean
annotationWire.xml (一定记得配置context:annotation-config/)
xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:context="http://springframework.org/schema/context" xmlns:p="http://springframework.org/schema/p" xsi:schemaLocation="http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd http://springframework.org/schema/context https://springframework.org/schema/context/spring-context.xsd">
xmlns:xsi="http://w3.org/2001/XMLSchema-instance"
xmlns:context="http://springframework.org/schema/context" xmlns:p="http://springframework.org/schema/p"
xsi:schemaLocation="http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd http://springframework.org/schema/context https://springframework.org/schema/context/spring-context.xsd">
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.ApplijYTUdvoHcationContext;
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实体。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~