我正試圖做一個新的簡單的Spring啓動應用程序演示依賴注入。我想用@Autowired註解導入bean。使用基於java的批註的彈簧汽車電線豆
這是我的代碼樣品片
---- ---- Example.class
package com.example.project;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*;
@RestController
@EnableAutoConfiguration
public class Example {
@Autowired
public myBean first;
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}
}
---- ---- myBean.class
package com.example.project;
public class myBean {
myBean()
{
System.out.println("Hi myBean Constructed");
}
}
--- BeanConfiguration.class ---
package com.example.project;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ComponentScan;
@Configuration
@ComponentScan(basePackages = "com.example.project")
public class BeanConfigurationClass {
@Bean
public myBean getBean()
{
return new myBean();
}
}
--pom.xml ---
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>example</groupId>
<artifactId>1</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.2.5.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
但是當我嘗試運行應用程序是無法找到豆和第一提供了以下錯誤 場com.example.project.Example需要一個bean無法找到類型爲「com.example.project.myBean」的類型。
我也嘗試使用基於xml的配置,但面臨同樣的錯誤。 這裏有什麼根本性的錯誤。
感謝您的期待。
嘗試添加公共訪問器構造爲myBean,從控制器中刪除@EnableAutoConfiguration和移動BeanConfigurationClass – kuhajeyan