package com.autowiring; public class AutoService { private AutoDao aotudao1; public AutoService(AutoDao aotudao1){ System.out.println("AutoService构造方法"); this.aotudao1 = aotudao1; } public void setAotudao1(AutoDao aotudao1) { System.out.println("AutoService set方法"); this.aotudao1 = aotudao1; } public void say(String word) { this.aotudao1.say(word); } }
package com.autowiring; import org.junit.Test; import com.imooc.test.base.UnitTestBase; public class AutoTest extends UnitTestBase{ public AutoTest(){ super("classpath*:spring.autowiring.xml"); } @Test public void testbyname(){ AutoService Service=super.getBean("auto"); Service.say("hello"); } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" default-autowire="byName"> <bean id="aotudao1" class="com.autowiring.AutoDao" ></bean> <bean id="auto" class="com.autowiring.AutoService"> </bean> </beans>
package com.autowiring; public class AutoDao { public void say(String word){ System.out.println("这是Dao层:"+word); } }
错误信息:No bean named 'auto' is defined
我的配置文件哪里错了
没有默认的无参构造方法,这个需要添加AutoService的无参构造方法,不然值为byname或者byType时候AutoService的构造函数会报错吧
<bean />
把 main 方法也放出来吧
在用 default-autowire的时候值为byname和bytype时 不能添加构造方法 在用constractor时可以用set方法
坑啊 这是为什么