How to configure Spring Repository to use mongoTemplate defined in xml bean? - spring

The code executes fine, but creates collections in default mongo database and location i.e in test database # localhost:27017. In the mongoTemplate bean wired through the below xml, I'm using mydb as database with mongod instance running at localhost:27018. However, the data still gets persisted to default instance and database.
MongoDB XML Bean defined in src/main/resources/mongo-context.xml:
<?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:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
<mongo:mongo id="mongo" host="localhost" port="27018"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongo" />
<constructor-arg value="mydb" />
</bean>
<mongo:repositories base-package="core.repository" mongo-template-ref="mongoTemplate"/>
</beans>
Playlist repository:
package core.repository;
import core.dao.Playlist;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.repository.Repository;
/**
* This repository provides CRUD operations for {#link core.dao.Playlist} objects.
*/
public interface PlaylistRepository extends Repository<Playlist, String> {
/**
* Finds the information of a single Playlist entry.
* #param id The id of the requested Playlist entry.
* #return The information of the found Playlist entry. If no Playlist entry
* is found, this method returns an empty {#link java.util.Optional} object.
*/
Optional<Playlist> findOne(String id);
/**
* Saves a new Playlist entry to the database.
* #param saved The information of the saved Playlist entry.
* #return The information of the saved Playlist entry.
*/
Playlist save(Playlist saved);
}
Playlist service that uses repository:
package core.service;
import core.dao.*;
import core.error.NotFoundException;
import core.repository.PlaylistRepository;
import core.simulator.PlaylistServiceSimulator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Executes the business logic promised by the {#link core.service.PlaylistService} interface.
*/
#Service
final class PlaylistServiceExecutor implements PlaylistService {
private static final Logger LOGGER = LoggerFactory.getLogger(PlaylistServiceExecutor.class);
private final PlaylistRepository repository;
private final PlaylistServiceSimulator simulator;
#Autowired
PlaylistServiceExecutor(PlaylistRepository repository, PlaylistServiceSimulator simulator) {
this.repository = repository;
this.simulator = simulator;
}
#Override
public PlaylistDTO create(PlaylistDTO playlist) {
LOGGER.debug("Creating a new Playlist entry with information: {}", playlist);
Playlist persisted = Playlist.build()
persisted = repository.save(persisted);
LOGGER.debug("Created a new Playlist entry with information: {}", persisted);
return persisted.toDTO();
}
#Override
public PlaylistDTO findById(String id) {
LOGGER.debug("Finding Playlist entry with id: {}", id);
Playlist found = findPlaylistById(id);
LOGGER.debug("Found Playlist entry: {}", found);
return found.toDTO();
}
private Playlist findPlaylistById(String id) {
Optional<Playlist> result = repository.findOne(id);
return result.orElseThrow(() -> new NotFoundException(id));
}
}
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>myapp</groupId>
<artifactId>core</artifactId>
<version>0.1</version>
<properties>
<!-- Enable Java 8 -->
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Configure the main class of our Spring Boot application -->
<start-class>core.CoreApp</start-class>
</properties>
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.9.RELEASE</version>
</parent>
<dependencies>
<!-- Get the dependencies of a web application -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<!-- Spring Data MongoDB-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>1.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.5</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>0.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path-assert</artifactId>
<version>0.9.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Spring Boot Maven Support -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Finally, SpringApplication boot class CoreApp:
package core;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* This configuration class has three responsibilities:
* <ol>
* <li>It enables the auto configuration of the Spring application context.</li>
* <li>
* It ensures that Spring looks for other components (controllers, services, and repositories) from the
* <code>core</code> package.
* </li>
* <li>It launches our application in the main() method.</li>
* </ol>
*/
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class CoreApp {
public static void main(String[] args) {
SpringApplication.run(CoreApp.class, args);
}
}

I'm assuming you're using Spring boot for it's auto configuration features and opinionated defaults. If so, you should let Spring configure your Mongo repository.
Remove your mongo configuration in src/main/resources/mongo-context.xml
Replace the mongo dependency
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
with the following Spring boot dependency to pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
Make sure your repositories extend MongoRepository
Have at least the following properties in your application.properties. See Spring Boot appendix for properties reference
spring.data.mongodb.uri=mongodb://localhost:27018/mydb
spring.data.mongo.repositories.enabled=true
Here are some additional guides:
https://spring.io/guides/gs/accessing-data-mongodb/
http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-nosql.html

You can use applicationContext.xml file for this. It looks like below:
<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true" 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:util="http://www.springframework.org/schema/util" xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">
<description><![CDATA[
Main entry point for spring configuration
]]></description>
<!-- Connection to MongoDB server -->
<mongo:db-factory host="localhost" port="27017" dbname="test" />
<!-- MongoDB Template -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
<!-- Package w/ automagic repositories -->
<mongo:repositories base-package="com.bedas.ays.mongo" />
</beans>

Related

Error creating bean with name 'opBean' defined in class path resource [applicationContext.xml]

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'opBean' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: com/springlearn/operation (wrong name: com/springlearn/Operation)
Operation.java
package com.springlearn;
public class Operation {
public void msg() {System.out.println("MSG Invoked");}
public int m() {
System.out.println("M invoked");
return 2;
}
public int k() {
System.out.println("K invoked");
return 3;
}
}
TrackOperation.java
package com.springlearn;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class TrackOperation {
#Pointcut("execution(* operation .*(..))")
public void k() {
}
#Before("k()")
public void myadvice(JoinPoint jp) {
System.out.println("Additional Concern");
}
}
Test.java
package com.springlearn;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test
{
public static void main( String[] args )
{
ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");
Operation e=(Operation)context.getBean("opBean");
System.out.println("Calling MSG");
e.msg();
System.out.println("Calling M");
e.m();
System.out.println("Calling K");
e.k();
}
}
applicationContext.xml
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="opBean" class="com.springlearn.Operation"> </bean>
<bean id="trackMyBean" class="com.springlearn.TrackOperation"></bean>
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"></bean>
</beans>
pom.xml
<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>SpringLearn</groupId>
<artifactId>springlearn</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springlearn</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>3.0.5.RELEASE</spring.version>
</properties>
<dependencies>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Make sure that in your aspect class the Target object class is spelt correctly under the pointcut expression
#Pointcut("execution(* Operation.*(..))")
//Operation class instead of operation case sensitivity

Spring boot #Configurable

I'm trying to configure Autowired in non-spring managed class under spring boot application.
I run successfully this under web application deployed under tomcat server.
But when i want run this under spring boot nothing works.
I made very simple app to check this functionality:
Console result from web app int tomcat:
...:::TEST CONTROLLER
...:::TEST autowired in cotrnoller: com.mycompany.test_aop.Test#30ea7445
...:::NEW
...:::Check: com.mycompany.test_aop.Test#30ea7445
Console result from spring boot app:
...:::TEST CONTROLLER
...:::TEST autowired in cotrnoller: com.mycompany.test_aop.Test#627ae77d
...:::NEW
...:::Check: null
I read a lot of topics hot to configure spring boot app but nothing works.
I trying set param -javaagent to spring-instrument.jar but no effect.
I struggle with this for three days but no effect
App:
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>pl.com.eurohost</groupId>
<artifactId>aop_test</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<repositories>
<repository>
<id>unknown-jars-temp-repo</id>
<name>A temporary repository created by NetBeans for libraries and jars it could not identify. Please replace the dependencies in this repository with correct ones and delete this repository.</name>
<url>file:${project.basedir}/lib</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>1.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>1.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>1.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.2.5.RELEASE</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-agent</artifactId>
<version>2.5.6.SEC03</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.3.3.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Main.class:
package com.mycompany.test_aop;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.EnableLoadTimeWeaving;
import org.springframework.context.annotation.aspectj.EnableSpringConfigured;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
#SpringBootApplication
#EnableSpringConfigured
#EnableAspectJAutoProxy
#EnableLoadTimeWeaving
#ComponentScan(value = "com.mycompany.test_aop")
public class Main {
public static void main(String args[]) {
SpringApplication.run(Main.class, args);
}
#Bean
public InstrumentationLoadTimeWeaver loadTimeWeaver() throws Throwable {
InstrumentationLoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
return loadTimeWeaver;
}
}
Web.java:
package com.mycompany.test_aop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class web {
#Autowired
Test t;
#RequestMapping(value = "/")
public #ResponseBody String root(){
System.out.println("...:::TEST CONTROLLER");
System.out.println("...:::TEST autowired in cotrnoller: "+t);
Test2 a = new Test2();
a.check();
return "HI!";
}
}
Test.java:
package com.mycompany.test_aop;
import org.springframework.stereotype.Service;
#Service
public class Test {
public void display() {
System.out.println("...:::TEST CLASS CALL DISPLAY");
}
}
Test2.java
package com.mycompany.test_aop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
#Configurable
public class Test2 {
#Autowired
private Test t;
public Test2() {
System.out.println("...:::NEW");
}
public void check() {
System.out.println("...:::Check: "+t);
}
}
Webapp has different pom, addittional file app-servlet.xml and no main method:
Main.java
package com.mycompany.test_aop;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableLoadTimeWeaving;
import org.springframework.context.annotation.aspectj.EnableSpringConfigured;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#EnableSpringConfigured
#EnableLoadTimeWeaving
#ComponentScan(value = "com.mycompany.test_aop")
#Configuration
#EnableWebMvc
public class Main extends WebMvcConfigurerAdapter {
}
app-servlet.xml:
<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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:default-servlet-handler/>
<context:annotation-config/>
<bean class="com.mycompany.test_aop.Main"/>
<mvc:annotation-driven>
</mvc:annotation-driven>
</beans>
By using Autowire Annotations.
#Autowired
Test2 a;
#RequestMapping(value = "/")
public #ResponseBody String root(){
System.out.println("...:::TEST CONTROLLER");
System.out.println("...:::TEST autowired in cotrnoller: "+t);
Test2 a = new Test2();//instead of this use autowired of test2
a.check();
return "HI!";
If you give thisTest2 a=new Test2();It will initiate with new Object then it will show only NULL

Spring support for WebHDFS

Is there any Spring support for wedhdfs? I didnt find any useful link on google.
I want to connect to hadoop with normal authentication and kerberos authentication via webhdfs. Is this supported in spring?
Any useful links will be helpful.
Thanks
Yes, Spring Data supports this. According to this documentation, it's possible to configure any supported Hadoop file system:
http://docs.spring.io/spring-hadoop/docs/current/reference/html/fs.html
SHDP does not enforce any specific protocol to be used - in fact, as
described in this section any FileSystem implementation can be used,
allowing even other implementations than HDFS to be used.
See below for a code sample that demonstrates auto-wiring a WebHDFS FileSystem instance into a command-line application. To run this, pass file paths as command line arguments, and it will list every file present at that path by calling FileSystem.listStatus.
The code sample is configured to connect to an unsecured WebHDFS instance with "simple" authentication. To connect to a WebHDFS instance secured with Kerberos, you'd set up the relevant configuration properties in the <hdp:configuration id="hadoopConfiguration" /> bean. Hadoop security configuration is a very large topic. Rather than repeat the information, I'll just point to the documentation in Apache:
http://hadoop.apache.org/docs/r2.4.1/hadoop-project-dist/hadoop-common/SecureMode.html
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test-spring-hadoop</groupId>
<artifactId>test-webhdfs</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Test Spring Hadoop with WebHDFS</name>
<description>Test Spring Hadoop with WebHDFS</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.0.RELEASE</version>
</parent>
<repositories>
<repository>
<id>spring-milestones</id>
<url>http://repo.spring.io/libs-release</url>
</repository>
</repositories>
<properties>
<start-class>testwebhdfs.Main</start-class>
<java.version>1.6</java.version>
<hadoop.version>2.4.1</hadoop.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-hadoop</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>${hadoop.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version>${hadoop.version}</version>
</dependency>
</dependencies>
</project>
src/main/resources/hadoop-context.xml
<?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:hdp="http://www.springframework.org/schema/hadoop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/hadoop http://www.springframework.org/schema/hadoop/spring-hadoop.xsd">
<hdp:configuration id="hadoopConfiguration" />
<hdp:file-system uri="webhdfs://localhost:50070" />
</beans>
src/main/java/testwebhdfs/Main.java
package testwebhdfs;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
#Configuration
#ImportResource("hadoop-context.xml")
public class Main implements CommandLineRunner {
#Autowired
private FileSystem fs;
#Override
public void run(String... strings) throws Exception {
Path[] paths = new Path[strings.length];
for (int i = 0; i < strings.length; ++i) {
paths[i] = new Path(strings[i]);
}
for (FileStatus stat: fs.listStatus(paths)) {
System.out.println(stat.getPath());
}
}
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}

org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:403)

I have run into this "WELD-001408 Unsatisfied dependencies for type [Injector] with qualifiers..." error when deploying a Maven project to Glassfish 4. I searched on the internet and added scope, added bean-discovery-mode="all", all other things and still could not get it work. I am learning Spring Framework and Java EE. Would someone please take a look at my code and help me out? Thanks!
stacktrace:
2014-01-28T11:29:44.755-0600|SEVERE: Exception while loading the app
2014-01-28T11:29:44.755-0600|SEVERE: Undeployment failed for context /MessageBoard
2014-01-28T11:29:44.786-0600|SEVERE: Exception while loading the app : CDI deployment failure:Exception List with 2 exceptions:
Exception 0 :
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [Injector] with qualifiers [#Default] at injection point [[BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedMethod] #Inject org.eclipse.sisu.inject.DefaultBeanLocator.autoPublish(Injector)]
at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:403)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:325)
at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:177)
at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:208)
at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:519)
at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:505)
at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:480)
at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:536)
at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:216)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:131)
at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:328)
codes:
package com.aaa.chapter5;
public class MessageBoardServiceImpl implements MessageBoardService {
private Map<Long, Message> messages = new LinkedHashMap<Long, Message>();
public List<Message> listMessages() {
return (List)messages.values();
}
public synchronized void postMessages(Message message) {
Long id = System.currentTimeMillis();
message.setId(id);
messages.put(id, message);
}
}
package com.aaa.chapter5.web;
// Bind controller to URL /reservationForm
// initial view will be resolved to the name returned in the default GET method
#Controller
#RequestMapping("/messagePost*")
#RequestScoped
//#SessionAttributes("message") // Command name class was used in earlier Spring versions
public class MessagePostController {
private MessageBoardService messageBoardService;
#Autowired
public void MessagePostController(MessageBoardService messageBoardService) {
this.messageBoardService = messageBoardService;
}
// Controller will always look for a default GET method to call first, irrespective of name
// In this case, named setupForm to ease identification
#RequestMapping(method = RequestMethod.GET)
public String setupForm(Model model) {
// Create inital message object
Message message = new Message();
// Add message to model so it can be display in view
model.addAttribute("message", message);
return "messagePost";
}
#RequestMapping(method = RequestMethod.POST)
public String onSubmit(#ModelAttribute("message") Message message, BindingResult result) { //, SessionStatus status) {
if (result.hasErrors()) {
// Errors, return to Form view
return "messagePost";
} else {
// No errors make reservation
messageBoardService.postMessages(message);
// Set complete, mark the handler's session processing as complete
// Allowing for cleanup of session attributes.
//status.setComplete();
// Redirect to reservationSuccess URL, defined in ReservationSuccessController
return "redirect:messageList";
}
}
}
pom.xml:
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.aaa.chapter5</groupId>
<artifactId>MessageBoard</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>MessageBoard Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<glassfish.directory>C:/Tools/glassfish4/glassfish</glassfish.directory>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.servlet.jsp.jstl</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-project</artifactId>
<version>3.0-alpha-2</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-artifact</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.maven.plugin</groupId>
<artifactId>maven-glassfish-plugin</artifactId>
<version>2.1</version>
<type>maven-plugin</type>
</dependency>
web.xml
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/board-service.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>board</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>board</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
board-service.xml
<?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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.aaa.chapter5" />
<mvc:annotation-driven />
board-servlet.xml
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.aaa.chapter5.web"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
<bean id="messageBoard"
class="com.aaa.chapter5.MessageBoardServiceImpl">
</bean>
</beans>

Spring #Autowired working without context:annotation-config [duplicate]

This question already has answers here:
Difference between <context:annotation-config> and <context:component-scan>
(15 answers)
Closed 3 years ago.
I've tested the behavior of auto wiring in case the context:annotation-config element is missing in the application context xml file. To my surprise it worked just the same.
So here is my question:
How come an AutowiredAnnotationBeanPostProcessor is registered in the ApplicationContext even though the context:annotation-config element is missing from the application context configuration file, or what else mechanism makes this configuration work?
I'm using Spring version 3.0.6.RELEASE
This is the project pom file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven- v4_0_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples.spring</groupId>
<artifactId>spring-utility</artifactId>
<version>1.0.0.CI-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring Utility</name>
<url>http://www.springframework.org</url>
<description>
<![CDATA[
This project is a minimal jar utility with Spring configuration.
]]>
</description>
<properties>
<maven.test.failure.ignore>true</maven.test.failure.ignore>
<spring.framework.version>3.0.6.RELEASE</spring.framework.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
This is the application context configuration file, with the context:annotation-config element commented out:
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<description>Example configuration to get you started.</description>
<!-- context:annotation-config/ -->
<context:component-scan base-package="com.foo.ch04" />
</beans>
A MessageProvider, that will be used as collaborator by a dependent bean MessageRenderer
package com.foo.ch04.helloworld;
import org.springframework.stereotype.Service;
#Service("messageProvider")
public class HelloWorldMessageProvider implements MessageProvider {
public String getMessage() {
return "Hello, World!";
}
}
The MessageRenderer, whose dependency messageProvider gets auto-injected:
package com.foo.ch04.helloworld;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service("messageRenderer")
public class StandardOutMessageRenderer implements MessageRenderer {
private MessageProvider messageProvider;
public void render() {
if (messageProvider == null) {
throw new RuntimeException(
"You must set the property messageProvider before rendering message.");
}
System.out.println(messageProvider.getMessage());
}
#Autowired
public void setMessageProvider(MessageProvider provider) {
messageProvider = provider;
}
public MessageProvider getMessageProvider() {
return messageProvider;
}
}
The test application loading the application context and testing the messageRenderer:
package com.foo.ch04.helloworld;
import org.springframework.context.support.GenericXmlApplicationContext;
public class DeclareSpringComponents {
public static void main(String[] args) {
GenericXmlApplicationContext context = new GenericXmlApplicationContext();
context.load("classpath:META-INF/spring/app-context-annotation.xml");
context.refresh();
MessageRenderer renderer = context.getBean("messageRenderer",
MessageRenderer.class);
renderer.render();
}
}
Even though the is missing in the application context configuration file, the message "Hello, World!" is written to stdout when the application is run.
The use of <context:component-scan /> implies annotation based configuration and as such specifying <context:annotation-config/> is redundant.
'context:annotation-config' This annotation-config tag is used to process the auto wired beans declared in the application context XML file. If the auto wired bean could be discovered using the scope of 'context:component-scan' tag then no need to use 'context:annotation-config' tag

Resources